2013-08-02 28 views
0

我知道如何使用Core Graphics繪製簡單的線條。我現在需要繪製尺寸線來進行測量。請參閱下面的圖片以獲取我需要繪製的示例(紅色)。頂線很容易,但在對角線上繪製垂線需要一些數學知識,我現在很難搞清楚。如何在iOS中使用Core Graphics來計算和繪製尺寸線(帶有垂直端線的線)?

每條主線都以(x,y)爲起點,以(x1,y1)爲終點。然後我需要繪製在每個點(x,y)和(x1,y1)相交的垂直線。

計算這些垂直線的點需要什麼數學計算?

enter image description here

回答

4

下面的代碼計算長度爲1的載體,其是垂直於 線從p = (x, y)p1 = (x1, y1)

CGPoint p = CGPointMake(x, y); 
CGPoint p1 = CGPointMake(x1, y1); 

// Vector from p to p1; 
CGPoint diff = CGPointMake(p1.x - p.x, p1.y - p.y); 
// Distance from p to p1: 
CGFloat length = hypotf(diff.x, diff.y); 
// Normalize difference vector to length 1: 
diff.x /= length; 
diff.y /= length; 
// Compute perpendicular vector: 
CGPoint perp = CGPointMake(-diff.y, diff.x); 

現在,添加和減去垂直矢量到的倍數第一點 以獲得第一標記線的端點p

CGFloat markLength = 3.0; // Whatever you need ... 
CGPoint a = CGPointMake(p.x + perp.x * markLength/2, p.y + perp.y * markLength/2); 
CGPoint b = CGPointMake(p.x - perp.x * markLength/2, p.y - perp.y * markLength/2); 

對於第二條標記線,只需重複上一次計算,即p1而不是p

+0

這是完美的,謝謝! – thephatp