iOS给imageView添加圆角

imgView.layer.cornerRadius=10;

// 这一行代码是很消耗性能的

imgView.clipsToBounds=YES;

好处是使用简单,操作方便。坏处是离屏渲染(off-screen-rendering)需要消耗性能。对于图片比较多的视图上,不建议使用这种方法来设置圆角。通常来说,计算机系统中CPU、GPU、显示器是协同工作的。CPU计算好显示内容提交到GPU,GPU渲染完成后将渲染结果放入帧缓冲区。

简单来说,离屏渲染,导致本该GPU干的活,结果交给了CPU来干,而CPU又不擅长GPU干的活,于是拖慢了UI层的FPS(数据帧率),并且离屏需要创建新的缓冲区和上下文切换,因此消耗较大的性能。


给UIImage添加生成圆角图片的扩展API:

-(UIImage*)hyb_imageWithCornerRadius:(CGFloat)radius{

CGRectrect=(CGRect){0.f,0.f,self.size};

UIGraphicsBeginImageContextWithOptions(self.size,NO,UIScreen.mainScreen.scale);

CGContextAddPath(UIGraphicsGetCurrentContext(),

[UIBezierPathbezierPathWithRoundedRect:rectcornerRadius:radius].CGPath);

CGContextClip(UIGraphicsGetCurrentContext());

[selfdrawInRect:rect];

UIImage*image=UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

returnimage;

}

然后调用时就直接传一个圆角来处理:

imgView.image=[[UIImage imageNamed:@"test"]hyb_imageWithCornerRadius:4];

这么做就是on-screen-rendering了,通过模拟器->debug->Color Off-screen-rendering看到没有离屏渲染了!(黄色的小圆角没有显示了,说明这个不是离屏渲染了)


在画之前先通过UIBezierPath添加裁剪,但是这种不实用:

-(void)drawRect:(CGRect)rect{

CGRectbounds=self.bounds;

[[UIBezierPathbezierPathWithRoundedRect:rectcornerRadius:8.0]addClip];

[self.imagedrawInRect:bounds];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容