2011-05-09 92 views
2

我使用swt gc繪製圖像。我的程序的一個選項是旋轉圖像。我也畫一個矩形作爲邊框。要旋轉我使用以下代碼:旋轉後的矩形座標

Transform oldTransform = new Transform(gc.getDevice()); 
    gc.getTransform(oldTransform); 

    Transform transform = new Transform(GCController.getCanvas().getDisplay()); 
    transform.translate(this.x+width/2, this.y+height/2); 
    transform.rotate(rotation); 
    transform.scale(this.scaleX, this.scaleY); 
    transform.getElements(elements); 
    transform.translate(-this.x-width/2, -this.y-height/2); 

    gc.setTransform(transform); 
    gc.drawImage(image, this.x, this.y);    
    gc.setTransform(oldTransform); 

    transform.dispose(); 

旋轉後,我想計算矩形的角位置。 我是想這樣的事情:

int tx = (this.x+width/2); 
    int ty = (this.y+height/2); 

    double rot = rotation * Math.PI/180; 

    double newX = tx*Math.cos(rot) - ty*Math.sin(rot); 
    double newY = tx*Math.sin(rot) + ty*Math.cos(rot); 

但如我所料不工作。

我已經使用變換矩陣我歌廳爲元素數組每次轉換之後也嘗試:

int tx = (this.x+width/2); 
    int ty = (this.y+height/2); 

    double newX = this.x * elements[0] + this.y * elements[2]; 
    double newY = this.x * elements[1] + this.y * elements[3]; 

但它給相同的結果,如使用等式旋轉。有任何想法嗎 ?

我已經解決了它:

int tx = (-width/2); 
    int ty = (-height/2); 

    double rot = rotation * Math.PI/180; 

    double newX = (tx)*Math.cos(rot) - (ty)*Math.sin(rot) + this.x + width/2; 
    double newY = (tx)*Math.sin(rot) + (ty)*Math.cos(rot) + this.y + height/2; 

我不得不回到0,0。進行旋轉並在旋轉後將其翻轉回來。

回答

1

您只需將變換矩陣乘以矩形中每個點的位置矢量。

Transform類大概有這樣做的方法(有意義),但我找不到可讀的「swt gc」API文檔,所以我不能告訴你它是什麼。

+0

它給了我相同的結果 – nasirus1983 2011-05-09 10:50:08

+0

也許你需要記住將矩形的位置本身添加到每個頂點的座標。 – James 2011-05-09 11:09:33