Why does BitmapFactory.decodeResource scale my image?

那年仲夏 提交于 2019-11-28 01:27:02

The default drawable directory assumes that images need to be scaled from the default mdpi size. Put your images in drawable-nodpi if you want to disable resource scaling.

Do note that a 120x120px image, if displayed on the screen, will be 3x smaller on a xxhdpi device compared to a mdpi device (as there are three times as many pixels per inch).

That's because the density of your screen and your image are different. Then if you do not specify Options system will do it for you. At the source of BitmapFactory you could see this:

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);
}

Therefore to prevent scaling you need to specify Options param with inScaled=false param. Or put your image to the res/drawable-nodpi folder.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!