1.圆角性能优化
在APP开发中,圆角图片还是经常出现的。如果一个界面中只有少量圆角图片或许对性能没有非常大的影响,但是当圆角图片比较多的时候就会APP性能产生明显的影响。我们设置圆角一般通过如下方式:
imageView.layer.cornerRadius=CGFloat(10);
imageView.layer.masks ToBounds=YES;
这样处理的渲染机制是GPU在当前屏幕缓冲区外新开辟一个 渲染缓冲区进行工作,也就是离屏渲染,这会给我们带来额外的性能损耗,如果这样的圆角操作达到一-定数量, 会触发 缓冲区的频繁合并和上下文的的频繁切换,性能的代价会宏观地表现在用户体验上一一掉帧。
优化方案:使用贝塞尔曲线UIBezierPath和Core Graphics框架画出一个圆角
extension UIView {
/// BezierPath 圆角设置
func roundCorners(_ corners: UIRectCorner = .allCorners, radius: CGFloat) {
let maskPath = UIBezierPath(
roundedRect: bounds,
byRoundingCorners: corners,
cornerRadii: CGSize(width: radius, height: radius))
let shape = CAShapeLayer()
shape.path = maskPath.cgPath
layer.mask = shape
}
}
2.设置不同大小的圆角
iOS开发中偶尔也能遇到需要设置不同大小圆角的需求,那么就需要绘制path来实现,具体代码如下
extension UIView {
//添加4个不同大小的圆角
func addCorner(cornerRadii:CornerRadii){
let path = createPathWithRoundedRect(bounds: self.bounds, cornerRadii:cornerRadii)
let shapLayer = CAShapeLayer()
shapLayer.frame = self.bounds
shapLayer.path = path
self.layer.mask = shapLayer
}
//各圆角大小
struct CornerRadii {
var topLeft :CGFloat = 0
var topRight :CGFloat = 0
var bottomLeft :CGFloat = 0
var bottomRight :CGFloat = 0
}
//切圆角函数绘制线条
func createPathWithRoundedRect( bounds:CGRect,cornerRadii:CornerRadii) -> CGPath
{
let minX = bounds.minX
let minY = bounds.minY
let maxX = bounds.maxX
let maxY = bounds.maxY
//获取四个圆心
let topLeftCenterX = minX + cornerRadii.topLeft
let topLeftCenterY = minY + cornerRadii.topLeft
let topRightCenterX = maxX - cornerRadii.topRight
let topRightCenterY = minY + cornerRadii.topRight
let bottomLeftCenterX = minX + cornerRadii.bottomLeft
let bottomLeftCenterY = maxY - cornerRadii.bottomLeft
let bottomRightCenterX = maxX - cornerRadii.bottomRight
let bottomRightCenterY = maxY - cornerRadii.bottomRight
//虽然顺时针参数是YES,在iOS中的UIView中,这里实际是逆时针
let path :CGMutablePath = CGMutablePath();
//顶 左
path.addArc(center: CGPoint(x: topLeftCenterX, y: topLeftCenterY), radius: cornerRadii.topLeft, startAngle: CGFloat.pi, endAngle: CGFloat.pi * 3 / 2, clockwise: false)
//顶右
path.addArc(center: CGPoint(x: topRightCenterX, y: topRightCenterY), radius: cornerRadii.topRight, startAngle: CGFloat.pi * 3 / 2, endAngle: 0, clockwise: false)
//底右
path.addArc(center: CGPoint(x: bottomRightCenterX, y: bottomRightCenterY), radius: cornerRadii.bottomRight, startAngle: 0, endAngle: CGFloat.pi / 2, clockwise: false)
//底左
path.addArc(center: CGPoint(x: bottomLeftCenterX, y: bottomLeftCenterY), radius: cornerRadii.bottomLeft, startAngle: CGFloat.pi / 2, endAngle: CGFloat.pi, clockwise: false)
path.closeSubpath();
return path;
}
}