9

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

Loktar
  • 34,764
  • 7
  • 90
  • 104
omega
  • 40,311
  • 81
  • 251
  • 474

1 Answers1

16

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);
Kai
  • 15,284
  • 6
  • 51
  • 82
  • RectF parameters requires the x,y indexes for left, top, right, and bottom. So isn't it canvasWidth-1 and canvasHeight-1? – omega Dec 14 '14 at 03:49
  • Think of it as your computer monitor: assuming it's FHD (1920x1080), when you want to fill the whole screen, you would draw from (0, 0) to (1920, 1080) and not (0, 0) to (1919, 1079), it's the same logic here. – Kai Dec 14 '14 at 03:58
  • But thats assuming the logic is where its up to but not including that length. But the documentation for new RectF says `Parameters: left The X coordinate of the left side of the rectangle top The Y coordinate of the top of the rectangle right The X coordinate of the right side of the rectangle bottom The Y coordinate of the bottom of the rectangle`. – omega Dec 14 '14 at 04:02
  • It says `Avoid object allocations during draw/layout operations (preallocate and reuse instead) `. How can I get rid of this error? – Muhammed Aydogan Jun 13 '20 at 17:01
  • @MuhammedAydogan I assume you are trying to allocate/create/retrieve Bitmaps in `onDraw`, you should move those code elsewhere and store those Bitmaps in instance variables. – Kai Jun 14 '20 at 20:22
  • @Kai I put `createScaledBitmap` method to `onSizeChanged` method as @Alex248 said in here https://stackoverflow.com/a/17087449/10908886 – Muhammed Aydogan Jun 15 '20 at 12:17
  • @MuhammedAydogan `onSizeChanged` _is_ a layout operation though, this means every time `onSizeChanged` is called you'll potentially be allocating a new set of bitmaps – Kai Jun 17 '20 at 00:15