使用 UIBezierPath 在用户单击的位置绘制圆

Draw Circle where user clicks with UIBezierPath

我是 swift 的新手。我想在用户点击的那些像素上画圆。 这是我的代码,它正在绘制圆圈但不在我点击的地方.... 我想在用户点击的地方画圆....就像获取用户点击的坐标并将它们打印到控制台但我想更新 ovalsandcircles() 函数中的 x 和 y 参数。

提前致谢。

`import UIKit

class DemoView: UIView {

    var startX :CGFloat = 0.0
    var startY :CGFloat = 0.0
    var path: UIBezierPath!

   override init(frame: CGRect) {
    super.init(frame: frame)

     self.backgroundColor = UIColor.darkGray

    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }



    override func draw(_ rect: CGRect) {

        // Specify the fill color and apply it to the path.
        ovalsAndCircles()
        UIColor.orange.setFill()
        path.fill()

        Specify a border (stroke) color.
        UIColor.purple.setStroke()
        path.stroke()

    }

    func ovalsAndCircles () {
        self.path = UIBezierPath(ovalIn: CGRect(x: startX,
                                                y: startY,
                                                width: 200,
                                                height: 200))

    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let point = touches.first!.location(in: self)
        startX = point.x
        startY = point.y
        print(startY)
        print(startX)


    }

}
`

先看看iOS中的坐标系:https://developer.apple.com/library/archive/documentation/General/Conceptual/Devpedia-CocoaApp/CoordinateSystem.html

CGRect 的来源 属性 类型为 CGPoint。也许它有助于在 draw 函数中设置矩形的原点:

let rect: CGRect = .... 
rect.origin = CGPoint(x:0.5, y:0.5) //Set the origin to the middle of the rect

您调用 touchesBegan 方法来设置应该绘制的点。但是当用户在屏幕上移动时,它不会被识别。使用 touchesEnded 方法代替

(1) 通过 Interface Builder 添加一个 UIView 控件。

(2) 将 UIView 控件的 class 名称设置为 DemoView

(3) 创建 UIView 的子 class 作为 DemoView 如下。

import UIKit

class DemoView: UIView {
    let fillColor = UIColor.green
    let strokeColor = UIColor.black
    let radius: CGFloat = 100.0

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = event?.allTouches?.first
        if let touchPoint = touch?.location(in: self) {
            drawCircle(point: touchPoint)
        }
    }

    func drawCircle(point: CGPoint) {
        if let subLayers = self.layer.sublayers {
            for subLayer in subLayers {
                subLayer.removeFromSuperlayer()
            }
        }

        let circlePath = UIBezierPath(arcCenter: point, radius: radius, startAngle: CGFloat(0), endAngle: CGFloat(Double.pi * 2.0), clockwise: true)
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = circlePath.cgPath
        shapeLayer.fillColor = fillColor.cgColor
        shapeLayer.strokeColor = strokeColor.cgColor
        self.layer.addSublayer(shapeLayer)
    }
}