2017-01-16 31 views
0

你好同事,Java Image Rotation無法正常工作

我正在製作遊戲,我希望能夠旋轉我的圖像。 我不使用Graphics2d,因爲我自己做了渲染類(大部分)。

的問題是,我目前的旋轉法葉孔新(旋轉)圖片還沒有將新的像素上的正確位置......

我沒有看到這個問題,所以也許你可以幫助:)

public void drawRotatedImage(Image image, int offX, int offY, double degree){ 
    int Iwidth = image.width; 
    int Iheight = image.height; 

    double angle = Math.toRadians(degree); 
    double sin = Math.sin(angle); 
    double cos = Math.cos(angle); 
    double x0 = 0.5 * (Iwidth - 1);  // point to rotate about 
    double y0 = 0.5 * (Iheight - 1);  // center of image 

    for(int x = 0; x < Iwidth; x++){ 
     for(int y = 0; y < Iheight; y++){ 
      double a = x - x0; 
      double b = y - y0; 
      int xx = (int) (+a * cos - b * sin + x0); 
      int yy = (int) (+a * sin + b * cos + y0); 

      if(xx >= 0 && xx < width && yy >= 0 && yy < height){ 
       setPixel(x+offX, y+offY, image.pixels[xx + yy*image.width]); 
      } 
     } 
    } 
} 

對setPixel函數如下所示:

public void setPixel(int x, int y, int color){ 
    if((x < 0 || x >= width || y < 0 || y >= height) || color == 0xffff00ff){ 
     return; 
    } 
    pixels[x + y * width] = color; 


} 

這工作得很好非旋轉的影像......但是當我旋轉它給人怪異的狗屎 除了當我使用完美的廣場作爲圖像,然後旋轉像90或180 但除此之外,我得到的圖像充滿了洞和錯誤的像素....

所以要清楚它不是一個錯誤或類似的東西那...我只是在尋找更好的解決方案或填補漏洞。

+0

爲什麼就不能'X0 = 0.5 * Iwidth' &&'Y0 = 0.5 * Iheight'? – TiMr

+0

因爲這不是中間 – Neriesta

+0

看你的語言,這不是你的後院! – gpasch

回答

0

的問題是,你正在設置源(原)旋轉之前與目的地的色點:

setPixel(x+offX, y+offY, image.pixels[xx + yy*image.width]);// you get the color of destination (xx,yy) and set it to source (x,y). 

這就是爲什麼它的工作原理:當次數爲180,因爲操作的反向看起來正確雖然它仍然被扭轉。

正確的方法是:

setPixel(xx+offX, yy+offY, image.pixels[x+ y*image.width]); 
+0

好吧,那真的是我的壞...但我仍然在我的新形象中漏洞... – Neriesta