- A+
所属分类:android
Bitmap.createScaledBitmap宽度不正确
出错场景
使用Bitmap.createScaledBitmap()方法后,宽度为屏幕宽度,但是显示出来的图片的宽度跟屏幕宽度不一致。
出错示例代码如下(1080为屏幕宽度):
ImageView imageView = new ImageView(this);
Bitmap bmp = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(
getResources(),R.drawable.layabox),1080,80,true);
imageView.setImageBitmap(bmp);
Bitmap.createScaledBitmap()函数说明
/**
* Creates a new bitmap, scaled from an existing bitmap, when possible. If the
* specified width and height are the same as the current width and height of
* the source bitmap, the source bitmap is returned and no new bitmap is
* created.
*
* @param src The source bitmap.
* @param dstWidth The new bitmap's desired width.
* @param dstHeight The new bitmap's desired height.
* @param filter true if the source should be filtered.
* @return The new scaled bitmap or the source bitmap if no scaling is required.
* @throws IllegalArgumentException if width is <= 0, or height is <= 0
*/
public static Bitmap createScaledBitmap (Bitmap src, int dstWidth, int dstHeight, boolean filter)
解决方法
利用setScaleType函数,设置缩放类型为不按比例缩放图片,即可。代码如下:
ImageView imageView = new ImageView(this);
Bitmap bmp = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(
getResources(),R.drawable.layabox),1080,80,true);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageBitmap(bmp);