2016-02-10 39 views
0

我在這裏和谷歌上找不到其他問題的答案。如何在畫布中調整位圖大小?

問題是,在GameView中創建的位圖在某些屏幕上太大(在我的Galaxy S5上它們是正確的),它們應該用theGameView.getDensity()進行縮放。

GameView類:

bmp = BitmapFactory.decodeResource(getResources(), R.drawable.circle_green); 

Circle類:

private int score; 
private int y = 0; 
private int x = 0; 
private int Speed, width, height; 
private GameView theGameView; 
private Bitmap bmp; 
private Random rnd; 

public Circle(GameView theGameView, Bitmap bmp) { 
    this.theGameView = theGameView; 
    this.bmp = bmp; 
    this.width = bmp.getWidth(); 
    this.height = bmp.getHeight(); 
    this.score = theGameView.getScore(); 

    rnd = new Random(); 
    x = (int) (30 * theGameView.getDensity() + rnd.nextInt((int) (theGameView.getWidth() - width - 50 * theGameView.getDensity()))); 
    y = (int) (60 * theGameView.getDensity() + rnd.nextInt((int) (theGameView.getHeight() - height - 80 * theGameView.getDensity()))); 
    Speed = (int) (2 * theGameView.getDensity()); 
} 

private void bounceOff() { 
    if (x + 10 * theGameView.getDensity() > theGameView.getWidth() - width - Speed || x + Speed < 10 * theGameView.getDensity()) { 
     Speed = -Speed; 
    } 

    x = x + Speed; 

    if (y + 60 * theGameView.getDensity() > theGameView.getHeight() - height - Speed || y + Speed < 60 * theGameView.getDensity()) { 
     Speed = -Speed; 
    } 

    y = y + Speed; 
} 

public void onDraw(Canvas canvas) { 
    bounceOff(); 
    if(canvas != null) { 
     canvas.drawBitmap(bmp, x, y, null); 
    } 
} 

public boolean isTouched(float x2, float y2) { 
    return x2 > x && x2 < x + width && y2 > y && y2 < y + height; 
} 

回答

0

這很容易。只需使用canvas.scale

canvas.save();    // Save current canvas params (not only scale) 
    canvas.scale(scaleX, scaleY); 
    canvas.restore();   // Restore current canvas params 

scale = 1.0f也會得出同樣的可見大小的位圖