我想基本上从屏幕上的一个点到另一个点(触摸开始和当前触摸的位置)绘制一条宽度为10的线,我认为最好的方法是找到高度和宽度,然后将其旋转到正确的位置。好吧,我最终得到了它,但有些奇怪的事情正在发生,我对Swift一无所知,所以我希望有人在这里有解释。这是相关代码
var touchBox: UIImageView!
var touchOrigin: CGPoint!
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
let position = touch?.location(in: self.view)
touchOrigin = CGPoint(x: (position?.x)!, y: floors[fromFloor].image.frame.origin.y + 10)
touchBox = UIImageView(image: UIImage(named: "lineImg"))
touchBox.frame = CGRect(x: (position?.x)!, y: (position?.y)!, width: 20, height: 20)
touchBox.alpha = 0.5
self.view.addSubview(touchBox)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
let position = touch?.location(in: self.view)
let x = min(touchOrigin!.x, (position?.x)!)
let y = min(touchOrigin!.y, (position?.y)!)
let w = max(touchOrigin!.x, (position?.x)!) - x
let h = max(touchOrigin!.y, (position?.y)!) - y
let angle = atan(h / w)
touchBox.removeFromSuperview()
touchBox = UIImageView(image: UIImage(named: "lineImg"))
let hyp = sqrt(pow(h, 2) + pow(w, 2))
// since it rotates around the center I have to find a new x, y
let x1 = (2 * x + w) / 2
let y1 = (2 * y + h) / 2 - (hyp / 2)
touchBox.frame = CGRect(x: x1, y: y1, width: 10, height: hyp)
// my image has arrows which is why I need to flip it sometimes
if (touchOrigin!.y < (position?.y)!) {
touchBox.transform = CGAffineTransform.init(scaleX: -1, y: -1)
}
if ((touchOrigin!.x < (position?.x)!) == (touchOrigin!.y < (position?.y)!)) {
touchBox.transform = touchBox.transform.rotated(by: -1 * (CGFloat(M_PI_2) - angle))
} else {
touchBox.transform = touchBox.transform.rotated(by: (CGFloat(M_PI_2) - angle))
}
touchBox.alpha = 0.5
self.view.addSubview(touchBox)
}
这个版本按照我想要的方式工作。然而,奇怪的是,每次通过touchesMoved我必须重新定义touchBox才能使其正常工作。如果我删除它(它已经被定义了)和其他相关的行(removeFromSuperview,alpha,addSubview),屏幕上生成的图像的宽度大于10(当我打印宽度时我可以确认这一点)。或者,如果我这样做并删除旋转图像的线条,它不会明显旋转,但宽度确实保持在10。
我尝试用它来旋转它
touchBox.transform = CGAffineTransform(rotationAngle: (CGFloat(M_PI_2) - angle))
但同样的问题发生了。有谁有想法吗?提前谢谢!