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

时间:2018-11-02 11:21:35

标签: swift uibezierpath

我是新手。我想在用户点击的那些像素上绘制圆形。  这是我的代码,它是画圆,而不是单击的地方...。 我想在用户单击的位置绘制一个圆。...就像在用户单击的位置获取坐标并将其打印到控制台一样,但是我想更新椭圆和圆函数中的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)


    }

}
`

3 个答案:

答案 0 :(得分:0)

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

#import "myObjCClass.h" #import "ProjectName-Swift.h" @implementation myObjCClass @end 的原始属性类型为CGRect。也许有助于在CGPoint函数中设置矩形的原点:

draw

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

(2)将该UIView控件的类名设置为DemoView

(3)如下创建UIView的子类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)
    }
}