Android - scaling image after I did it programmatically
Strange thing happens - at least I don't get it.
I have an image (w: 120px, h: 63px) which is presented on one ImageButton. The only variant of that image that I have is placed in drawable-hdpi (and there is no other drawable directory). Everything is ok with this image and every resolution (density), Android takes care of it very nicely.
But, trouble is when I take a photo from an album (some very big photo, for example), scale it to dimensions of a button (previously mentioned, w: 120px h: 63px) and set that small image as ImageButton background.
In case when I am testing on emulator with medium density (160) it is ok, but when testing on device with high density button gets resized since scaled image appears smaller.
Does anyone has an idea what is happening and why is size of image changed once more after I scaled it?
Any clue will be highly appreciated.
Here is the code I use for resizing the image:
public static void resizeAndSaveImage(String pathToResize, int newWidth, int newHeight, FileOutputStream output) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.开发者_高级运维inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(pathToResize), null, options);
if (bitmap != null) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
output.close();
}
} catch (Exception e) {
// ...
}
Dimension parameters are passed in as follows: newWidth = 120, newHeight = 63.
In order to achieve what you want you need to use density-independent pixels (dp) and not physical pixels. Reading from here:
The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, the baseline density assumed by the platform (as described later in this document). At run time, the platform transparently handles any scaling of the dp units needed, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: pixels = dps * (density / 160). For example, on 240 dpi screen, 1 dp would equal 1.5 physical pixels. Using dp units to define your application's UI is highly recommended, as a way of ensuring proper display of your UI on different screens.
In order to explain in more detail why this is happening with one image (album photo) and not with an image resource, you need to post the code you are using for the scaling.
精彩评论