2017-05-03 53 views
0

我尝试了太多等式来获得正确的答案,可能是代码有问题或者我对该想法的理解。然而,这里是我的代码:制作UIImageView(图像的箭头)指向我在屏幕上触摸的位置

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { 
    if let touch = touches.first { 
     let coord = touch.location(in:view) 
     self.linegu.transform = CGAffineTransform.init(rotationAngle: atan((coord.y - (self.view.center.y + (self.view.center.y)/2.5))/(coord.x - self.view.center.x))) 
    } 
} 

linegu是我使用的UIImageView我在取景当中使用此代码它定位:

let Ypos = (self.view.center.y/2.5); 
self.linegu.center = self.view.center 
self.linegu.center.y = (self.view.center.y + Ypos) 

wherever I touch the screen, the arrow points toward a different point =(

+0

图片上是不可见的,但我想你错了90度。尝试从结果中加入或减去90度。请提供点击照片的地方。 – Sergey

+0

也许,你需要提供一个项目。 我用你的代码创建了一个演示项目。 它的工作。 https://github.com/sunbohong/Demo-Collection/commit/3ed6f593a1fa3dde5e489165821033ed6e02631f#diff-86182cc774e7f14dc3e6cf106edaa8f1 –

+0

我会尽量减去也许我可以把它弄清楚。 –

回答

1

不要紧,在图像视图的位置。你应该扔掉你的“幻数”2.5。你正在超越这一点。

假设arrow是图像视图,并且它始于水平方向,箭头指向右侧。并假设背景视图上有一个轻击手势识别器。 (为简单起见,我们使用轻击手势识别器;它看起来像您最终可能会想要使用平移手势识别器。但现在,让我们来看看这个东西的工作原理。)

然后这里是如何轻敲手势的动作处理程序看:

let c = self.arrow.center 
    let p = t.location(in: self.arrow.superview) 
    let angle = atan2(p.y - c.y, p.x - c.x) 
    self.arrow.transform = CGAffineTransform(rotationAngle:angle) 

就这么简单。

enter image description here

+0

谢谢,你的回答帮了很多 –

+0

但角度不够准确:(请看这个链接http:// gph。是/ 2qz4dgI –

+0

我不知道你是什么意思。 _Touches_不是很准确(你的手指很胖),但数学很精确。我的屏幕截图中的线条指向我点击的位置。 – matt

0

为什么你用这个奇怪的公式吗?

CGAffineTransform.init(rotationAngle: atan((coord.y - (self.view.center.y + (self.view.center.y)/2.5))/(coord.x - self.view.center.x))) 

这个2.5分配器从哪里来?


大约只用.center.frameUIImageView什么位置?

像:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    if let touch = touches.first { 
     let location = touch.location(in: view) 
     imageView.center = location // may need to apply some offset here, depending on where exactly the arrow points in the arrow image 
    } 
} 
+0

该公式基本上是两点之间的角度。 tan-1 [(y2-y1)/(x2-x1)] –

+0

2.5是在y轴上得到较低的箭头 –

+0

因此,y1和x1代表固定点,我已经在代码 –

相关问题