通过 UIBezierPath 与 CAShapeLayer 为 UIView 添加边框

通过贝塞尔曲线与 CAShapeLayer 为 View 添加虚线边框,可设置宽度,颜色,圆角等

在这里插入图片描述

代码如下:

	/// 为视图添加虚线边框
   ///
   /// - Parameters:
   ///   - view: 要添加边框的视图
   ///   - size: 视图 size
   ///   - cornerRadius: 视图圆角 默认:10
   ///   - lineWidth: 边框宽 默认: 1
   ///   - lineColor: 边框颜色 默认: black
   ///   - lineDashPattern: 边框段长和间距 默认: [5,3]
   func addBorderLine(view:UIView, size:CGSize, cornerRadius:CGFloat = 10, lineWidth:CGFloat = 1, lineColor:Color? = Color.black, lineDashPattern: [NSNumber] = [5,3]) -> Void {
       let shaplayer = CAShapeLayer()
       shaplayer.bounds = CGRect.init(x: 0, y: 0, width: size.width, height: size.height)
       shaplayer.anchorPoint = CGPoint.init(x: 0, y: 0)
       shaplayer.fillColor = Color.clear.cgColor
       shaplayer.strokeColor = lineColor?.cgColor
       shaplayer.lineWidth = lineWidth
       shaplayer.lineJoin = "miter"
       shaplayer.lineDashPattern = [5,3]
       let path = CGMutablePath()
       path.move(to: CGPoint.init(x: lineWidth / 2, y: cornerRadius + lineWidth / 2))
       path.addArc(center: CGPoint.init(x: cornerRadius + lineWidth / 2, y: cornerRadius + lineWidth / 2), radius: cornerRadius, startAngle: .pi, endAngle: .pi / 2 * 3, clockwise: false)
       path.addLine(to: CGPoint.init(x: size.width - cornerRadius - lineWidth / 2, y: lineWidth / 2))
       path.addArc(center: CGPoint.init(x: size.width - cornerRadius - lineWidth / 2, y: cornerRadius + lineWidth / 2), radius: cornerRadius, startAngle: .pi / 2 * 3, endAngle: .pi * 2, clockwise: false)
       path.addLine(to: CGPoint.init(x: size.width - lineWidth / 2, y: size.height - cornerRadius - lineWidth / 2))
       path.addArc(center: CGPoint.init(x: size.width - cornerRadius - lineWidth / 2, y:  size.height - cornerRadius - lineWidth / 2), radius: cornerRadius, startAngle: 0, endAngle: .pi / 2, clockwise: false)
       path.addLine(to: CGPoint.init(x: cornerRadius + lineWidth / 2, y: size.height - lineWidth / 2))
       path.addArc(center: CGPoint.init(x: cornerRadius + lineWidth / 2, y:  size.height - cornerRadius - lineWidth / 2), radius: cornerRadius, startAngle: .pi / 2, endAngle: .pi, clockwise: false)
       path.addLine(to: CGPoint.init(x: lineWidth / 2, y: cornerRadius + lineWidth / 2))
       shaplayer.path = path
       view.layer.addSublayer(shaplayer)
       view.layer.masksToBounds = true
       view.layer.cornerRadius = cornerRadius
   }```

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值