Search code examples
swiftuibezierpath

Draw Circle where user clicks with UIBezierPath


I am new to swift. I want to draw Circle on those pixels where user clicks. Here is my code it is drawing circle but not at where I clicks.... I want to draw circle where user clicks....Like it is getting the coordinates where user clicks and printing them to console but I want to update the x and y arguments in ovalsandcircles() function.

Thanks in advance.

`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)


    }

}
`

Solution

  • (1) Add a UIView control through Interface Builder.

    (2) Set the class name of that UIView control to DemoView.

    (3) Create a subclass of UIView as DemoView as follows.

    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)
        }
    }