How to resize a bitmap in the best way in Android?

Suppose I have a hexagon:

hexagon

If I resize it to use it in my application, which contains a grid of hexagons:

// ... bgPaint = new Paint(); bgPaint.setAntiAlias(true); bgPaint.setDither(true); // ... Bitmap coloredBackground = BitmapFactory.decodeResource(getResources(), R.drawable.bg); // ... canvas.drawBitmap(coloredBackground, null, getAsRect(), bgPaint); 

I get this:

Hexagons

getAsRect() returns the Rect object that I use for drawing. I want to get rid of these transparent pixels around the edges. I think that I am doing something wrong, but have not yet found. Do you have any idea how I can solve this problem?

I tried experimenting with anti-aliasing and anti-aliasing, but nothing has changed.

+4
source share
4 answers

3 offers:

1

Try this: turn off system scaling when you decode a resource by setting BitmapFactory.Options.inScaled to false:

 Options options = new BitmapFactory.Options(); options.inScaled = false; Bitmap source = BitmapFactory.decodeResource(context.getResources(), R.drawable.bg, options); 

The inScaled flag should be disabled if you need an inScaled version of the bitmap.

Then scale the bitmap with Bitmap.createScaledBitmap(...) .

2

Another possible reason is that your black diagonal tile lines contain different shades of gray:

This is a close-up of your tile:

enter image description here

It smoothes out before resizing. Any pixels that are not completely black can appear as a lighter color in the changed lines. You can change the lines of the lines to be completely black (0xFF000000), and do the smoothing only after resizing.

3

Another solution to this problem is to create your tile as follows:

enter image description here

This avoids the problem of drawing two smoothed diagonal lines next to each other.

+7
source

Why not use this one instead?

 Bitmap.createScaledBitmap(decodedBitmap, targetWidth, targetHeight, true); 
+1
source

You can try the hqx resizing algorithm:

Alternatively, you can paint on a large surface and scale that surface completely.

+1
source

I resize the images as follows:

  String url = ""; //replace with path to your image int imageDimension = 48; // replace with required image dimension //decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(url), null, o); //Find the correct scale value. It should be the power of 2. final int REQUIRED_SIZE = imageDimension; int width_tmp = o.outWidth, height_tmp = o.outHeight; int scale = 1; while(true){ if(width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) break; width_tmp /= 2; height_tmp /= 2; scale *= 2; } //decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; Drawable drawable = new BitmapDrawable(context.getResources(), BitmapFactory.decodeStream(new FileInputStream(url), null, o2)); 
0
source

All Articles