当Bitmap的宽度大于ImageView的最大显示宽度时对ImageView的宽高重新计算来适应Bitmap的宽高(转)
当bitmap的宽大于ImageView显示控件的宽度时,如果不对ImageView的宽高重新计算,那么Imageview的高度就会超过显示图片的高度,用户体验将会很差,所以我们需要重新计算显示控件的宽高,这里我们假定ImageView的最大宽度为屏幕的宽度。利用下面这个工具类就可以很好解决问题了:
Android获取屏幕宽度和高度:
// WindowManager manage=getWindowManager();
// Display display=manage.getDefaultDisplay();
// 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", "原始图片高度:"+rawHeight+"原始图片宽度:"+rawWidth);
Log.i("hello", "原始高宽比:"+(rawHeight/rawWidth));
if(rawWidth > screenWidth){
height = (rawHeight/rawWidth)*screenWidth;
width = screenWidth;
}else{
width = rawWidth;
height = rawHeight;
}
Log.i("hello", "处理后图片高度:"+height+"处理后图片宽度:"+width);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams((int)width, (int)height);
return layoutParams;
}