2017-05-03 52 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代表固定點,我已經在代碼 –

相關問題