2011-11-09 58 views
0

我在正確旋轉位圖時遇到問題。我有一個SurfaceView與多個位圖。這些位圖存在於數組列表中,並使用for循環,我爲onDraw方法中的每一個調用canvas.drawBitmap。Android中旋轉位圖的問題

@Override 
protected void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 
    canvas.drawColor(Color.BLACK); 

    for (int i = 0; i < jumper.size(); i++) { 
     canvas.drawBitmap(jumper.get(i).getGraphic(), jumper.get(i) 
       .getCoordinates().getX(), jumper.get(i).getCoordinates() 
       .getY(), null); 
    } 
} 

我試圖讓用戶選擇一個特定的位圖(許多之一),然後有位旋轉,當用戶拖動他在屏幕上的手指。所以這裏是旋轉代碼。現在我只是使用默認的Android圖標(72x72px),該圖標位於屏幕中心附近的隨機位置。

private void rotateJumper(int direction) { 
    Matrix matrix = new Matrix(); 
    Bitmap source = jumper.get(selectedJumperPos).getGraphic(); 
    matrix.postRotate(direction, source.getWidth()/2, 
      source.getHeight()/2); 
    int x = 0; 
    int y = 0; 
    int width = 72; 
    int height = 72; 
    Bitmap tempBitmap = Bitmap.createBitmap(source, x, y, width, height,  
      matrix, true); 
    jumper.get(selectedJumperPos).setGraphic(tempBitmap); 
} 

取決於手指拖動的方向,整數方向是+1或-1。所以圖像應該爲每個MotionEvent.ACTION_MOVE事件旋轉1度。

這裏有問題:

  1. 圖像不繞圖像中心。 CW旋轉中心在左下角。 CCW旋轉中心位於右上角。
  2. 由於它不圍繞中心旋轉,因此圖像在其初始邊界之外旋轉並最終消失。
  3. 圖像在旋轉時變得模糊。

任何幫助你可以給我將不勝感激。

謝謝!

回答

0

使用矩陣繪製現有的位圖到畫布上,而不是創建一個新位圖:

@Override 
protected void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 
    canvas.drawColor(Color.BLACK); 

    for (int i = 0; i < jumper.size(); i++) { 
     canvas.drawBitmap(jumper.get(i).getGraphic(), jumper.get(i).getMatrix(), null); 
    } 
} 

private void rotateJumper(int direction) { 
    Matrix matrix = jumper.get(selectedJumperPos).getMatrix(); 
    if(matrix == null) { 
     matrix = new Matrix(); 
     matrix.setTranslate(jumper.get(...).getCoord...().getX(), jumper.get(..).getCoord...().getY()); 
     jumper.get(selectedJumperPos).setMatrix(matrix); 
    } 
    Bitmap source = jumper.get(selectedJumperPos).getGraphic(); 
    matrix.postRotate(direction, source.getWidth()/2, 
      source.getHeight()/2); 

} 
+0

這工作。採取了相當大的重新設計,但它的工作。謝謝! – phoenixfire53

+0

@ FunKTheMonk,你能解釋一下你的代碼嗎? – Manikandan

+0

每次旋轉發生時,都不會創建新的位圖,而是在渲染過程中保留並使用矩陣。在rotateJumper中,我們只在需要時初始化一個矩陣,然後圍繞位圖的中心旋轉矩陣。在繪製位圖時,我們使用onDraw方法中的矩陣 - 矩陣可以包含將畫布繪製到畫布上的數據(翻譯),繪製(縮放)的大小以及旋轉的大小。 – FunkTheMonk

0

請原諒我的相當偏離的答案,但你的for -loop引起了我的注意。有可能以「更可讀」的格式編寫它;

for (YourJumperItem item : jumper) { 
    canvas.drawBitmap(
     item.getGraphic(), item.getCoordinates().getX(), 
     item.getCoordinates().getY(), null); 
} 

哪裏YourJumperItem是類鍵入您的跳投 - 陣列包含的內容。不幸的是,我們不能多說旋轉位圖,只是推廣這種方便的書寫方式。

+0

感謝。我是Java新手,所以很高興知道。 – phoenixfire53