2012-06-25 15 views
5

我掙扎繪製圍繞其中心旋轉的位圖,也沒有調整的位圖旋轉。我正在通過遊戲線程將所有的精靈畫到屏幕上,所以我正在尋找一種合併原始位圖而不是畫布的解決方案。的Android繞中心位不調整

在此先感謝。

這是到目前爲止我的代碼,它繞其中心位圖,但調整它的大小。

i = i + 2; 
      transform.postRotate(i, Assets.scoresScreen_LevelStar.getWidth()/2, Assets.scoresScreen_LevelStar.getHeight()/2); 
      Bitmap resizedBitmap = Bitmap.createBitmap(Assets.scoresScreen_LevelStar, 0, 0, Assets.scoresScreen_LevelStar.getWidth(), Assets.scoresScreen_LevelStar.getHeight(), transform, true); 

      game.getGraphics().getCanvasGameScreen().drawBitmap(resizedBitmap, null, this.levelStar.getHolderPolygons().get(0), null); 

更新:

我發現這並不像聽起來那麼容易。我的旋轉代碼不是問題。位圖旋轉,但dst矩形也將不得不根據旋轉角度增加/減小,否則bimap將顯得更小,因爲它被繪製到固定的dst矩形中。 所以我猜我必須開發一些方法,將返回一個dst矩形。 因此,沒有位圖旋轉所需要的方式出現調整:

public static Bitmap rotateBitmap(Bitmap bitmap, int rotation) // I've got this method working 

public static Rect rotateRect(Rect currentDst, int rotation) // Don't got this 

我明白這將需要一些數學(三角函數),任何人都做好了迎接挑戰? :P

+0

你到目前爲止嘗試過什麼?你能發表一些什麼不適合你的例子嗎? –

+0

Straight Android或Cocos2d-x? – Fallenreaper

+0

更新的代碼問題,@Fallenreaper,我使用自己的GE,所以直截了當的Android。 –

回答

0

這對我有效!

我創建的返回一個矩陣的方法。該矩陣可用於以下繪圖方法:

public void drawBitmap (Bitmap bitmap, Matrix matrix, Paint paint) 

在這裏,你去! (參數形狀可以輕鬆地更換,如果你想的是,僅僅發表評論):

public static Matrix rotateMatrix(Bitmap bitmap, Shape shape, int rotation) { 

     float scaleWidth = ((float) shape.getWidth())/bitmap.getWidth(); 
     float scaleHeight = ((float) shape.getHeight())/bitmap.getHeight(); 

     Matrix rotateMatrix = new Matrix(); 
     rotateMatrix.postScale(scaleWidth, scaleHeight); 
     rotateMatrix.postRotate(rotation, shape.getWidth()/2, shape.getHeight()/2); 
     rotateMatrix.postTranslate(shape.getX(), shape.getY()); 


     return rotateMatrix; 

    } 

注意:如果你想要一個動畫旋轉,旋轉參數必須與新值更新一次框架例如。 1然後2然後3 ...

7

你應該吸取使用Matrix類的位圖。假設您想旋轉「Ship」類中的圖像,下面是一個非常基本的想法。您更新更新方法中的當前位置矩陣。在onDraw()中,使用新更新的位置矩陣繪製位圖。這將繪製旋轉的位圖而不調整其大小。

public class Ship extends View { 

    private float x, y; 
    private int rotation; 
    private Matrix position;  
    private Bitmap bitmap; 

    ... 

    @Override 
    public void onDraw(Canvas canvas) { 
     // Draw the Bitmap using the current position 
     canvas.drawBitmap(bitmap, position, null); 
    } 

    public void update() { 
     // Generate a new matrix based off of the current rotation and x and y coordinates. 
     Matrix m = new Matrix(); 
     m.postRotate(rotation, bitmap.getWidth()/2, bitmap.getHeight()/2); 
     m.postTranslate(x, y); 

     // Set the current position to the updated rotation 
     position.set(m); 

     rotation += 2; 
    } 

    .... 

} 

希望幫助!

也請記住,你生成的遊戲循環中一個新的Bitmap對象將需要大量資源。

+0

你能重寫,我可以調用一個名爲rotateBitmap(位圖位圖,INT旋轉)靜態方法,會返回一個位圖旋轉BIMAP對象? –

+0

該方法改變你傳入的位圖,所以你的私有變量「private Bitmap bitmap」不旋轉。只要做「返回位圖」;並更改方法簽名。 – Aziz

+0

對不起,這不適合我。 –