绘制半径等于手指路径的圆

时间:2019-10-22 21:46:52

标签: ios swift uikit

我想创建一个应用程序,用户将一根手指放在屏幕上,并在屏幕上绘制一个圆圈。圆心位于用户触摸屏幕的位置。用户移动他们的手指以增加圆的半径。当用户移动手指时,将画出圆圈,圆圈的边缘位于用户的手指下方。

现在,我的代码创建了一个随机半径的圆,其圆心在用户触摸屏幕的位置。我需要帮助弄清楚如何使圆的半径取决于用户的手指路径。

所以我有一个CircleView类:UIView这是可可粉触摸类。它具有以下功能:

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.clear
    }

    override func draw(_ rect: CGRect) {
        // Get the Graphics Context
        if let context = UIGraphicsGetCurrentContext() {

        // Set the circle outerline-width
        context.setLineWidth(5.0);

        // Set the circle outerline-colour
        UIColor.green.set()

        // Create Circle
        let center = CGPoint(x: frame.size.width/2, y: frame.size.height/2)
        let radius = (frame.size.width - 10)/2
        context.addArc(center: center, radius: radius, startAngle: 0.0, endAngle: .pi * 2.0, clockwise: true)

        // Draw
        context.strokePath()
        }

我的类ViewController:UIViewController现在具有以下功能:

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.lightGray
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            // Set the Center of the Circle
            // 1
            let circleCenter = touch.location(in: view)

            // Set a random Circle Radius
            // 2
            let circleWidth = CGFloat(25 + (arc4random() % 50))
            let circleHeight = circleWidth

            // Create a new CircleView
            // 3
            let circleView = CircleView(frame: CGRect(x: circleCenter.x, y: circleCenter.y, width: circleWidth, height: circleHeight))
            view.addSubview(circleView)
        }
    }

我想创建一个圆,它的半径不是随机的,而是用户可以通过拖动手指设置的半径。将来,我还将希望为我的应用实现删除和移动模式。移动模式将使用户在屏幕上拖动圆圈。

1 个答案:

答案 0 :(得分:0)

好吧,同意@Marina的评论。只需您必须为用户的手指方向添加检查,因为触摸将返回CGPoint(x:,y:)。

let initialRadius = 0
var currentRadius = 10


func touchBegan(...){ 
initialRadius = currentRadius

}
func touchMoves(...) {

Y = touch(in view).Y
X = touch(in view).x

if direction == vertical {
     currentdistance = substract point Y from first touch (center.Y)
(after that you have to abs() current distance for negative value)
  currentRadius =  abs(currentdistance)

} else if direction == horizontal {  currentdistance = substract point X from first touch  (center.X)
(after that you have to abs() current distance for negative value)
currentRadius =  abs(currentdistance)
} else {

either X or Y

}
}

func touchEnded(...){

drawcircle(radius)
相关问题