UIBezierPath 画不规则带圆角图形

实现效果如下

前言

   公司由于想实现如上的需求,想了很久,于是乎自己实现了一个这样的制作过程。

实现方案如下:

import UIKit

class KBDraw: UIView {

   
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        myDraw()
    }
    
    func myDraw() {
        /*
         * 这里发现其实压根不需要画中间的线。直接画圆觉弧度 就可以实现了()
         */
        let radius :CGFloat = 10
        UIColor(r: 255, g: 0, b: 0, a: 100).setFill()
        //        UIColor.orange.setFill()
        UIColor.yellow.setStroke()
        let offset :CGFloat = 40
        let bezierPath = UIBezierPath()
        bezierPath.move(to: CGPoint(x: 10 + offset, y: 10))
        bezierPath.addLine(to: CGPoint(x: 100 + offset, y: 10))

        bezierPath.addArc(withCenter: CGPoint(x: 100 + offset, y: 10 + radius), radius: radius, startAngle: CGFloat(-Double.pi/2.0), endAngle: 0, clockwise: true)
        bezierPath.addArc(withCenter: CGPoint(x: 100 + offset, y: 100), radius: radius, startAngle: 0, endAngle: CGFloat(Double.pi/2.0), clockwise: true)
        bezierPath.addArc(withCenter:CGPoint(x: 50 + offset , y: 100 + radius + radius), radius: radius, startAngle: CGFloat(-Double.pi/2.0), endAngle: CGFloat(-Double.pi), clockwise: false)
//        bezierPath.addLine(to: CGPoint(x: 50 - radius + offset , y: 140 + radius + radius))
        bezierPath.addArc(withCenter:CGPoint(x: 50 - radius - radius + offset , y: 140 + radius + radius), radius: radius, startAngle:0, endAngle: CGFloat(Double.pi/2), clockwise: true)
//        bezierPath.addLine(to: CGPoint(x: 10 + offset, y: 140 + radius + radius  + radius))
        bezierPath.addArc(withCenter: CGPoint(x: 10 + offset - radius, y: 140 + radius + radius  ), radius: radius, startAngle: CGFloat(Double.pi/2.0), endAngle: CGFloat(Double.pi), clockwise: true)
        
//        bezierPath.addLine(to: CGPoint(x: 10 + offset - radius - radius, y: 10 + radius))
        bezierPath.addArc(withCenter: CGPoint(x: 10 + offset - radius , y: 10 + radius), radius: radius, startAngle: CGFloat(Double.pi), endAngle: CGFloat(Double.pi) * 3 / 2, clockwise: true)
        bezierPath.addLine(to:  CGPoint(x: 10 + offset, y: 10))
        
        bezierPath.lineWidth = 2.0
        bezierPath.setLineDash([3,2], count: 2, phase: 0)
        bezierPath.stroke()
        bezierPath.fill()
    }

}

其实 在本方案中,我发现不必设置中间的直线就可以实现这个效果,也是意外!

原文地址:https://www.cnblogs.com/kingbo/p/12162236.html