一、绘制圆角
View的四个角可以绘制想要的圆角:
.allCorners 四个角都是圆角
.topLeft 上左
.topRight 上右
.bottomLeft 下左
.bottomRight 下右
//画圆
let maskPath = UIBezierPath.init(roundedRect: self.agreeButton.bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize.init(width: 45/2, height: 45/2))
let maskLayer = CAShapeLayer.init()
maskLayer.frame = self.agreeButton.bounds
maskLayer.path = maskPath2.cgPath
self.agreeButton.layer.mask = maskLayer
二、绘制圆角的同时绘制边框
//画圆的同时画边框
let maskPath = UIBezierPath.init(roundedRect: self.refuseButton.bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize.init(width: 45/2, height: 45/2))
let maskLayer1 = CAShapeLayer.init()
maskLayer1.frame = self.refuseButton.bounds
maskLayer1.path = maskPath1.cgPath
maskLayer1.strokeColor = UIColor.RGBToColor(86, 155, 213).cgColor
maskLayer1.fillColor = UIColor.white.cgColor
maskLayer1.lineWidth = 1
self.refuseButton.layer.addSublayer(maskLayer1)
三、绘制边框
//画边
let linePath = UIBezierPath.init(rect: self.testView.bounds)
let shapeLayer = CAShapeLayer()
shapeLayer.frame = CGRect.init(x: 0, y:0, width: 100, height: 100)
shapeLayer.path = linePath.cgPath
shapeLayer.lineWidth = 1
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
self.testView.layer.addSublayer(shapeLayer)
四、绘制圆角和阴影
用UIBezierPath给View画阴影,需要重写View的draw(_ rect: CGRect)
方法
override func draw(_ rect: CGRect) {
//画圆角和阴影
let shadowPath = UIBezierPath(roundedRect: rect.insetBy(dx: 5, dy: 5), byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 10, height: 10))
let context = UIGraphicsGetCurrentContext()
context?.setShadow(offset: CGSize(width: 5, height:5), blur: 5, color: UIColor.black.cgColor)
UIColor.RGBToColor(86, 155, 213).setFill()
shadowPath.fill()
}
用UIBezierPath同时要实现任意圆角+阴影,只能通过在draw(_ rect: CGRect)
方法中实现,rect.insetBy(dx: 5, dy: 5)
导致空件大小比实际上小,但是值为0时又没有阴影效果。
用layer属性设置阴影比用UIBezierPath的效果好