iOS中为view添加圆角效果有两种方式,一种基于“离屏渲染”(off-screen-renderring),直接设置view的layer层参数即可简单实现,也很常用,但性能较低;另一种则是编写底层图形代码,实现‘在屏渲染’(on-screen-renderring),可以大大优化绘制性能。
iOS中圆角效果实现的最简单、最直接的方式,是直接修改View的layer层参数:
/* 设置圆角半径 */
view.layer.cornerRadius = 5;
/* 将边界以外的区域遮盖住 */
view.layer.masksToBounds = YES;
这种方法最简单快速,但其实这种方法的实现是靠的‘离屏渲染’(off-screen-rendering),性能很低。
另外一种则是实现on-screen-rendering,用于提高性能。
为UIImage类扩展一个实例函数:
/**
* On-screen-renderring绘制UIImage矩形圆角
*/
- (UIImage *)imageWithCornerRadius:(CGFloat)radius ofSize:(CGSize)size{
/* 当前UIImage的可见绘制区域 */
CGRect rect = (CGRect){0.f,0.f,size};
/* 创建基于位图的上下文 */
UIGraphicsBeginImageContextWithOptions(size, NO, UIScreen.mainScreen.scale);
/* 在当前位图上下文添加圆角绘制路径 */
CGContextAddPath(UIGraphicsGetCurrentContext(), [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius].CGPath);
/* 当前绘制路径和原绘制路径相交得到最终裁剪绘制路径 */
CGContextClip(UIGraphicsGetCurrentContext());
/* 绘制 */
[self drawInRect:rect];
/* 取得裁剪后的image */
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
/* 关闭当前位图上下文 */
UIGraphicsEndImageContext();
return image;
}
使用时,让实例化的UIImage对象调用一下上面的实例方法即可:
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];
/* 创建并初始化UIImage */
UIImage *image = [UIImage imageNamed:@"icon"];
/* 添加圆角矩形 */
image = [image imageWithCornerRadius:50 ofSize:imageView.frame.size];
[imageView setImage:image];
完整代码
14.pngUIImage类别扩展在屏渲染实例函数:
#import <UIKit/UIKit.h>
@interface UIImage (RadiusCorner)
/* On-screen-renderring绘制UIImage矩形圆角 */
- (UIImage *)imageWithCornerRadius:(CGFloat)radius ofSize:(CGSize)size;
@end
#import "UIImage+RadiusCorner.h"
@implementation UIImage (RadiusCorner)
/** * On-screen-renderring绘制UIImage矩形圆角 */
- (UIImage *)imageWithCornerRadius:(CGFloat)radius ofSize:(CGSize)size{
/* 当前UIImage的可见绘制区域 */
CGRect rect = (CGRect){0.f,0.f,size};
/* 创建基于位图的上下文 */
UIGraphicsBeginImageContextWithOptions(size, NO, UIScreen.mainScreen.scale);
/* 在当前位图上下文添加圆角绘制路径 */
CGContextAddPath(UIGraphicsGetCurrentContext(), [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius].CGPath);
/* 当前绘制路径和原绘制路径相交得到最终裁剪绘制路径 */
CGContextClip(UIGraphicsGetCurrentContext());
/* 绘制 */
[self drawInRect:rect];
/* 取得裁剪后的image */
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
/* 关闭当前位图上下文 */
UIGraphicsEndImageContext();
return image;
}
@end
测试代码:
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];
UIImage *image = [UIImage imageNamed:@"icon"];
/* 1. on-screen-renderring */
//image = [image imageWithCornerRadius:50 ofSize:imageView.frame.size];
[imageView setImage:image];
/* 2. off-screen-renderring */
imageView.layer.cornerRadius = 20;
imageView.layer.masksToBounds = YES;
[self.view addSubview:imageView];
}
@end
网友评论