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; } }