Dmitrij Kiltau
Dmitrij Kiltau

Reputation: 325

How to resize bitmap in canvas?

I can't find a answer on other questions here and on Google.

The problem is, that the Bitmaps created in GameView are too big on some screens (on my Galaxy S5 they are correct) and they should be scaled with theGameView.getDensity().

GameView class:

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

Circle class:

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

Upvotes: 0

Views: 589

Answers (1)

AndreyICE
AndreyICE

Reputation: 3624

It's very easy. Just use canvas.scale

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

scale = 1.0f will draw the same visible size bitmap

Upvotes: 1

Related Questions