2011-09-13 21 views
1

我正在嘗試爲Android製作遊戲。使用圖像調整位圖的大小,將其用作背景

現在我必須將圖像放入位圖並調整其大小以適應設備的寬度和高度。

當我試圖讓我看到圖片大於屏幕的圖片。我希望位圖適合屏幕。

感謝您的幫助。

這裏是我的代碼的一部分:

類GameView

bmp = BitmapFactory.decodeResource(getResources(), R.drawable.foto); 
background = new BackGround(this,bmp); 

類Background

public class BackGround { 

     private Bitmap bmp; 
     private int width; 
     private int height; 

     public BackGround(GameView gameView, Bitmap bmp) { 
      this.bmp = bmp; 
      this.width = bmp.getWidth(); 
      this.height = bmp.getHeight(); 
     } 
     public void onDraw(Canvas canvas) { 

      Rect src = new Rect(0, 0, width, height); 
      Rect dst = new Rect(0, 0, width, height); 
      canvas.drawBitmap(bmp, src, dst, null); 
     } 
} 

回答

3

我只是說這個代碼在我的onDraw動態基於大小在屏幕上(處理縱向和橫向模式)。

final int canvasWidth = getWidth(); 
final int canvasHeight = getHeight(); 

int imageWidth = originalImage.getWidth(); 
int imageHeight = originalImage.getHeight(); 

float scaleFactor = Math.min((float)canvasWidth/imageWidth, 
           (float)canvasHeight/imageHeight); 
Bitmap scaled = Bitmap.createScaledBitmap( originalImage, 
              (int)(scaleFactor * imageWidth), 
              (int)(scaleFactor * imageHeight), 
              true); 
+0

你添加到你的onDraw()?哦,親愛的.. – dcow

+0

哈,好點。我相信我有一個防範措施來防止每次都會發生縮放,但自那時起,我將縮放代碼移至更合適的位置 - surfaceCreated()(另一個用於更新圖像時)。它更乾淨,更高效。 – ProjectJourneyman

0

Rect dst = new Rect(0,0,canvas.getWidth(),canvas.getHeight());

相關問題