高效添加圆角效果

高效添加圆角效果

逻辑思路: 切换到工作线程利用CoreGraphic API生成一个offscreen UIImage,再切换到main thread赋值给UIImageView。这里还涉及到UIImageView复用,圆角头像cache缓存(不能每次都去绘制)

设置圆角,最简单的情况下既没有 off-screen render,也没有降低帧数

view.layer.cornerRadius = 5

但是 cornerRadius 这个属性只会影响背景颜色和border,对于内部还有子视图控件就不会出现这样的效果了所以这时候需要:

label.layer.cornerRadius = 5
label.layer.masksToBounds = true	

这时候就会出现离屏渲染了,当圆角视图较多时,就会使fps大幅度下降

为 UIView 添加圆角

利用 Core Graphics 自己画出了一个圆角矩形 UIImage。除了一些必要的代码外,最核心的就是 CGContextAddArcToPoint 函数。它中间的四个参数表示曲线的起点和终点坐标,最后一个参数表示半径。调用了四次函数后,就可以画出圆角矩形。最后再从当前的绘图上下文中获取图片并返回。

func kt_drawRectWithRoundedCorner(radius radius: CGFloat,
                              borderWidth: CGFloat,
                              backgroundColor: UIColor,
                              borderColor: UIColor) -> UIImage {    
UIGraphicsBeginImageContextWithOptions(sizeToFit, false, UIScreen.mainScreen().scale)
let context = UIGraphicsGetCurrentContext()

CGContextMoveToPoint(context, 开始位置);  // 开始坐标右边开始
CGContextAddArcToPoint(context, x1, y1, x2, y2, radius);  // 这种类型的代码重复四次

CGContextDrawPath(UIGraphicsGetCurrentContext(), .FillStroke)
let output = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return output
}

有了这个图片后,我们创建一个 UIImageView 并插入到视图层级的底部:

 extension UIView {
func kt_addCorner(radius radius: CGFloat,
                  borderWidth: CGFloat,
                  backgroundColor: UIColor,
                  borderColor: UIColor) {
    let imageView = UIImageView(image: kt_drawRectWithRoundedCorner(radius: radius,
                                borderWidth: borderWidth,
                                backgroundColor: backgroundColor,
                                borderColor: borderColor))
    self.insertSubview(imageView, atIndex: 0)
}
}	

提醒

无论使用上面哪种方法,你都需要小心使用背景颜色。因为此时我们没有设置 masksToBounds,因此超出圆角的部分依然会被显示。因此,你不应该再使用背景颜色,可以在绘制圆角矩形时设置填充颜色来达到类似效果。

其他方法

  • 美工切图无法适用有背景图的场景
  • shouldRasterize也有cache实效问题

原文链接:iOS 高效添加圆角效果实战讲解


posted @ 2016-03-18 15:27  孙焱焱  阅读(1105)  评论(0编辑  收藏  举报