平时开发没到遇到获取位图资源时,常常会这样用:
Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.mipmap.bt_find_pressed);
Drawable drawable=getResources().getDrawable(R.mipmap.bt_find_pressed);
殊不知这样得来的位图资源并不是真实的原图,它们是经过系统裁剪匹配后返回的,即基于Androd系统的DPI机制实现屏幕适配。而且当你把一个图片放到XXHDPI目录中时,在不同尺寸屏幕获取的位图资源尺寸大小并不一样。有时反倒是获取图片资源的原始尺寸成了问题,昨天看了一下午,终于搞清楚了原因。
在BitmapFactory类中:
/**
* Decode a new Bitmap from an InputStream. This InputStream was obtained from
* resources, which we pass to be able to scale the bitmap accordingly.
*/
public static Bitmap decodeResourceStream(Resources res, TypedValue value,
InputStream is, Rect pad, Options opts) {
if (opts == null) {
opts = new Options();
}
if (opts.inDensity == 0 && value != null) {
final int density = value.density;
if (density == TypedValue.DENSITY_DEFAULT) {
opts.inDensity = DisplayMetrics.DENSITY_DEFAULT;
} else if (density != TypedValue.DENSITY_NONE) {
opts.inDensity = density;
}
}
if (opts.inTargetDensity == 0 && res != null) {
opts.inTargetDensity = res.getDisplayMetrics().densityDpi;
}
return decodeStream(is, pad, opts);
}
当你没有指定Options时,系统会生成默认值,而且会根据density的不同解码图片文件,这就导致了无法获取图片真实尺寸的问题。
而获取原始尺寸的方法就是自己配置一个BitmapFactory.Options:
//根据资源id获取图片资源的原始尺寸大小
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), item.getDrawableId(), options);
item.setSrcsize(new Point(options.outWidth, options.outHeight));
配置过BitmapFactory.Options后,系统就不会按照默认配置返回参数,你得到的位图信息就是基于原图大小的。