設置如圖紅色框里面的圓角樣式痴柔,帶邊框:
extension UIView {
? ? //各圓角大小
? ? struct CornerRadii {
? ? ? ? vartopLeft:CGFloat=0
? ? ? ? vartopRight:CGFloat=0
? ? ? ? varbottomLeft:CGFloat=0
? ? ? ? varbottomRight:CGFloat=0
? ? }
? ? //切圓角函數(shù)繪制線條
? ? 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
? ? ? ? //雖然順時針參數(shù)是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();
? ? ? ? returnpath;
? ? }
? ? //MARK:添加4個不同尺寸的圓角(可以設置邊框)
? ? func addCorner(cornerRadii:CornerRadii, size:CGSize, borderColor:UIColor, borderWidth:CGFloat) {
? ? ? ? let rect =CGRect(origin:CGPoint(x:0, y:0), size: size)
? ? ? ? let path =createPathWithRoundedRect(bounds: rect, cornerRadii:cornerRadii)
? ? ? ? let shapLayer =CAShapeLayer()
? ? ? ? shapLayer.frame= rect
? ? ? ? shapLayer.path= path
? ? ? ? self.layer.mask= shapLayer
? ? ? ? //設置邊框
? ? ? ? let borderLayer =CAShapeLayer()
? ? ? ? borderLayer.path= path
? ? ? ? borderLayer.fillColor=UIColor.clear.cgColor
? ? ? ? borderLayer.strokeColor= borderColor.cgColor
? ? ? ? borderLayer.lineWidth= borderWidth
? ? ? ? borderLayer.frame= rect
? ? ? ? self.layer.addSublayer(borderLayer)
? ? }
? ? //MARK:添加4個不同尺寸的圓角(不可以設置邊框)
? ? func addCorner(cornerRadii:CornerRadii, size:CGSize) {
? ? ? ? let rect =CGRect(origin:CGPoint(x:0, y:0), size: size)
? ? ? ? let path =createPathWithRoundedRect(bounds: rect, cornerRadii:cornerRadii)
? ? ? ? let shapLayer =CAShapeLayer()
? ? ? ? shapLayer.frame= rect
? ? ? ? shapLayer.path= path
? ? ? ? self.layer.mask= shapLayer
? ? }
}