在 UIBezierPath 中创建一个点

Create a point inside a UIBezierPath

我需要按照图片中的方式制作路径。我已经弄清楚了圆形部分,但仍然坚持如何将点放在圆形部分内。

创建一个全新的 UIView。在我的示例中,我将我的 ProdView 命名为 ProdView。复制以下代码:

    import UIKit

    @IBDesignable
    class ProdView: UIView {
        override func draw(_ rect: CGRect) {
        // Drawing code

        let lineWidth: CGFloat = 2.0

        let canvas = CGRect(x: rect.origin.x + 1, y: rect.origin.y + 1, width: rect.width - 2, height: rect.height - 2)

        let circlePath = UIBezierPath(ovalIn: canvas)

        UIColor.black.setStroke()

        UIColor.black.setFill()

        circlePath.lineWidth = lineWidth

        circlePath.stroke()

        let circleDotWidth: CGFloat = 10

        let circleDot = UIBezierPath(ovalIn: CGRect(x: -circleDotWidth / 2,
                                                y: -circleDotWidth / 2,
                                                width: circleDotWidth,
                                                height: circleDotWidth))

        let context = UIGraphicsGetCurrentContext()!

        context.translateBy(x: rect.width / 2, y: rect.height / 2)

        context.saveGState()

        let angle: CGFloat = (5 * CGFloat(Double.pi) / 3) - (CGFloat(Double.pi) / 2)

        context.rotate(by: angle)

        context.translateBy(x: 0, y: rect.height / 2 - (circleDotWidth / 2) + 4)

        circleDot.fill()

        context.restoreGState()

      }


    }

在上面的例子中,我创建了圆并给它画了笔画。然后我创建了圆点,考虑到它的 x 和 y CGRect 值的宽度。然后我获取当前上下文并将其转换到视图矩形的中心。然后我保存当前上下文并将上下文旋转到 5pi/3 弧度,我认为这非常接近你想要的点。我减去 pi/2 因为默认情况下上下文从起始角度(或 0)倾斜 pi/2 弧度。然后,考虑到圆点的宽度和圆的线宽,我将上下文翻译到我想要填充点的位置,并填充它以使其可见。

当我将 UIView 取出到 ViewController 上时,设置约束并将其 class 更改为 ProdView,我得到以下结果(记住 ProdView 是 IBDesignable,因此我们可以在 Storyboard 中看到结果):