omega
omega

Reputation: 43833

How to resize bitmap when drawing in canvas?

In my android app, I have this function that creates a new bitmap from an old one via canvas.

private static Bitmap convert(Bitmap bitmap, Bitmap.Config config, int width, int height) {
    Bitmap convertedBitmap = Bitmap.createBitmap(width, height, config);
    Canvas canvas = new Canvas(convertedBitmap);
    Paint paint = new Paint();
    paint.setColor(Color.BLACK);
    canvas.drawBitmap(bitmap, 0, 0, paint);
    bitmap.recycle();
    return convertedBitmap;
}

The problem is when I draw the old bitmap onto the canvas, since the old bitmap is bigger in dimensions than the canvas, only the top left part of the bitmap gets drawn on the canvas. Is there a way I can make it so when it draws the bitmap on the canvas, it scales the bitmap so it fits perfectly in the canvas?

I don't want to resize the bitmap using createScaledBitmap. Is there a faster way?

OR Can I do createScaledBitmap but make it mutable at the same time? That is what I am trying to do overall, resize and make mutable at same time.

Thanks

Upvotes: 9

Views: 16257

Answers (1)

Kai
Kai

Reputation: 15476

You can call public void drawBitmap (Bitmap bitmap, Rect src, RectF dst, Paint paint) for this function (Android Doc). The code below should accomplish what you are trying to do:

canvas.drawBitmap(bitmap, null, new RectF(0, 0, canvasWidth, canvasHeight), null);

Upvotes: 17

Related Questions