2011-06-21 88 views
11

我有谷歌地圖圖標,在使用MarkerImage在地圖上繪圖之前,需要旋轉某些角度。我使用PIL在Python中執行旋轉,生成的圖像與原始圖像大小相同 - 32x32。例如,使用以下默認谷歌地圖標記:獲取旋轉圖像中點的新x,y座標

# full_src is a variable holding the full path to image 
# rotated is a variable holding the full path to where the rotated image is saved 
image = Image.open(full_src) 
png_info = image.info 
image = image.copy() 
image = image.rotate(30, resample=Image.BICUBIC) 
image.save(rotated, **png_info) 

所得圖像是icon rotated 30 degrees counter-clockwise

棘手位是: icon before rotation ,一個30度康特時針旋轉,使用以下Python代碼實現在使用新的旋轉圖像創建MarkerImage時獲取新的錨點。這需要成爲圖標的尖端。默認情況下,定位點是底部中間[在x,y座標中定義爲(16,32),其中(0,0)是左上角]。有人可以向我解釋我怎樣才能在JavaScript中輕鬆解決這個問題?

謝謝。

更新2011年6月22日: 已張貼錯誤的旋轉圖像(原來是逆時針330度)。我糾正了這一點。還添加了重新採樣(Image.BICUBIC),使旋轉圖標更清晰。

+0

@Trufa:謝謝你的建議。 –

回答

20

要計算旋轉點的位置,您可以使用rotation matrix

轉換爲JavaScript,這種計算旋轉點:

function rotate(x, y, xm, ym, a) { 
    var cos = Math.cos, 
     sin = Math.sin, 

     a = a * Math.PI/180, // Convert to radians because that is what 
           // JavaScript likes 

     // Subtract midpoints, so that midpoint is translated to origin 
     // and add it in the end again 
     xr = (x - xm) * cos(a) - (y - ym) * sin(a) + xm, 
     yr = (x - xm) * sin(a) + (y - ym) * cos(a) + ym; 

    return [xr, yr]; 
} 

rotate(16, 32, 16, 16, 30); // [8, 29.856...] 
+0

謝謝。這正是我需要的。 –

+0

@Simon Kagwi:謝謝你糾正,不知道那裏發生了什麼...... – pimvdb

6

約0,0旋轉的公式是:

x1 = cos(theta) x0 - sin(theta) y0 
y1 = sin(theta) x0 + cos(theta) y0 

但是,這對於普通軸,繞0,0。 「圖形」軸順時針旋轉PIL。另外,它圍繞圖像的中心。最後令人困惑的是,圖像的大小可能會發生變化,這需要在最終結果中進行說明。

程序:取原點,減去圖像中心,應用「圖形軸」校正旋轉,找到新的圖像大小,加回新圖像的中心位置。

旋轉用圖形軸是:

x1 = cos(theta) x0 + sin(theta) y0 
y1 = -sin(theta) x0 + cos(theta) y0 

16,32 - 16,16爲0,16,旋轉30度順時針旋轉(基於你的圖像)給出一個點COS(-30)* 0 + sin(-30)* 16,-sin(-30)* 0 + cos(-30)* 16 = -8,13.86。最後一步是添加旋轉位置的中心位置。

+0

你能解釋一下「常規」和「圖形」軸之間的區別嗎?主要的不同似乎是哪個座標有一個減法,但我不明白爲什麼。 – Michael

0

在圖像,下爲正Y和向右爲正X.然而,應用rotation formula,我們需要向上爲正Y.因此,步驟1將應用f(x,y) = f(x,h-y),其中'h'是圖像的高度。假設圖像相對於x0,y0旋轉。那麼你需要將你的起源轉變爲這一點。因此,第2步將是f(x,y) = f(x-x0,y-y0)。在此階段(即兩步之後),您的新座標將爲​​,h-y-y0。您現在已準備好應用旋轉公式

x1 = x*cos(theta) - y*sin(theta) 

y1 = xsin(theta) + ycos(theta) 

使用步驟二後獲得的x和y的值。 你會得到

x1 = (x-x0)*cos(theta) - (h-y-y0)*sin(theta) 

y1 = (x-x0)*sin(theta) + (h-y-y0)*cos(theta) 

現在,撤消在步驟2和步驟1(按順序)完成轉換。

撤消第二步後:xNew = x1 + x0yNew = y1 + y0

撤銷第一步後:xNew = x1 + x0yNew = h - (y1 + y0)

這給了你:

xNew = (x-x0)*cos(theta) - (h-y-y0)*sin(theta) + x0 

yNew = -(x-x0)*sin(theta) - (h-y-y0)*cos(theta) + (h-y0)