如何在画布中调整位图大小?

时间:2016-02-10 19:47:37

标签: java android canvas bitmap

我无法在此处和Google上找到其他问题的答案。

问题是,在GameView中创建的位图在某些屏幕上太大了(在我的Galaxy S5上它们是正确的),它们应该使用GameView.getDensity()进行缩放。

GameView类:

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

圈子类:

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;
}

1 个答案:

答案 0 :(得分: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将绘制相同的可见大小位图