When bitmap is larger than the width of the imageview display control, if you do not recalculate the width and height of the imageview, the height of the imageview will exceed the height of the displayed image, and the user experience will be poor, therefore, we need to recalculate the width and height of the display control. Here we assume that the maximum width of imageview is the screen width. The following tool class can be used to solve the problem:
Android gets the screen width and height:
// Windowmanager manage = getwindowmanager ();
// Display = manage. getdefadisplay display ();
// Screenheight = display. getheight ();
// Screenwidth = display. getwidth ();
Inputstream is = getresources (). openrawresource (R. drawable. Sy );
Bitmap mbitmap = bitmapfactory. decodestream (is );
Linearlayout. layoutparams Lp = getlayoutparams (mbitmap, screenwidth );
Imageview1.setlayoutparams (LP );
Imageview1.setimagebitmap (mbitmap );
Public static linearlayout. layoutparams getlayoutparams (Bitmap bitmap, int screenwidth ){
Float rawwidth = bitmap. getwidth ();
Float rawheight = bitmap. getheight ();
Float width = 0;
Float Height = 0;
Log. I ("hello", "Original Image Height:" + rawheight + "Original Image Width:" + rawwidth );
Log. I ("hello", "original aspect ratio:" + (rawheight/rawwidth ));
If (rawwidth> screenwidth ){
Height = (rawheight/rawwidth) * screenwidth;
Width = screenwidth;
} Else {
Width = rawwidth;
Height = rawheight;
}
Log. I ("hello", "processed Image Height:" + height + "processed image width:" + width );
Linearlayout. layoutparams = new linearlayout. layoutparams (INT) width, (INT) height );
Return layoutparams;
}
When the width of bitmap is greater than the maximum display width of imageview, the width and height of imageview are recalculated to adapt to the width and height of Bitmap)