Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw smoothly scaled bitmaps on Canvas

This is how I draw Bitmap on Canvas in my Android app:

canvas.save(); canvas.scale(scale, scale, x, y); canvas.drawBitmap(bitmap, x, y, null); canvas.restore(); 

However the Bitmap is not scaled smoothly, no anti-aliasing is performed. How can I enable anti-aliasing?

like image 341
fhucho Avatar asked Nov 27 '10 21:11

fhucho


People also ask

How do I create a bitmap in canvas?

To create a bitmap object on a canvas C , use: id = C . create_bitmap( x , y , *options ...) which returns the integer ID number of the image object for that canvas.

Is canvas a bitmap?

Basically, the Canvas is backed by a Bitmap , so when you draw anything using the canvas, the canvas will draw into the Bitmap it was created with.

What is the use of bitmap canvas and Paint class?

Canvas API is a drawing framework that is provided in Android, with the help of which we can create custom shapes like rectangle, circle, and many more in our UI design. With the help of this API, we can draw any type of shape for our app. The drawing of the different shapes is done using Bitmap.

How canvas works in Android?

The Canvas class holds the "draw" calls. To draw something, you need 4 basic components: A Bitmap to hold the pixels, a Canvas to host the draw calls (writing into the bitmap), a drawing primitive (e.g. Rect, Path, text, Bitmap), and a paint (to describe the colors and styles for the drawing).


2 Answers

Try this:

Paint paint = new Paint(); paint.setAntiAlias(true); paint.setFilterBitmap(true); paint.setDither(true);  canvas.drawBitmap(bitmap, x, y, paint); 
like image 89
Vit Khudenko Avatar answered Sep 24 '22 01:09

Vit Khudenko


Both Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG); or paint.setFilterBitmap(true); worked for me but be very careful, on my game it cut down the FPS from 30FPS to 17FPS only. So if it is a mission critical drawing like in a game you better scale the image at loading time. Which I did in the following manner:

public Bitmap getImage (int id, int width, int height) {     Bitmap bmp = BitmapFactory.decodeResource( getResources(), id );     Bitmap img = Bitmap.createScaledBitmap( bmp, width, height, true );     bmp.recycle();     return img; } 
like image 34
Sileria Avatar answered Sep 20 '22 01:09

Sileria