Draw smoothly scaled bitmaps on Canvas

2019-01-21 06:35发布

问题:

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?

回答1:

Try this:

Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);

canvas.drawBitmap(bitmap, x, y, paint);


回答2:

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


回答3:

Have you tried creating a Paint object, calling setAntiAlias(true) on it and passing it to the drawBitmap method as the 4th parameter? If this does not work I guess you should scale down the drawBitmap call instead of scaling the Canvas, e.g. by using drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint).



回答4:

Use:

canvas.drawBitmap(source, 0, 0, new Paint(Paint.ANTI_ALIAS_FLAG));