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



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

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

所以我有一个类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()
}

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

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

好吧,同意@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)

最新更新