我有一个圆形的 UIView
我在上面加了一个虚线描边。
,,,
var view = CAShapeLayer()
view.strokeColor = UIColor.red.cgColor
view.lineDashPattern = [2, 2]
view.frame = addphotoView.bounds
view.fillColor = nil
view.path = UIBezierPath(rect: addphotoView.bounds).cgPath
view.cornerRadius = 16
view.masksToBounds = true
addphotoView.layer.addSublayer(yourViewBorder)
但是 view.cornerRadius
没有达到预期的效果。
角落被擦掉了
你应该四舍五入 Layer
s path
.
像这样。
borderLayer.path = UIBezierPath(roundedRect: addphotoView.bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 16, height: 16)).cgPath
你可以将所有这些逻辑移到一个扩展中。
extension UIView {
@discardableResult
func addLineDashedStroke(pattern: [NSNumber]?, radius: CGFloat, color: CGColor) -> CALayer {
let borderLayer = CAShapeLayer()
borderLayer.strokeColor = color
borderLayer.lineDashPattern = pattern
borderLayer.frame = bounds
borderLayer.fillColor = nil
borderLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius)).cgPath
layer.addSublayer(borderLayer)
return borderLayer
}
}
addphotoView.addLineDashedStroke(pattern: [2, 2], radius: 16, color: UIColor.gray.cgColor)