位图 getWidth 返回错误值 [英] Bitmap getWidth returns wrong value

查看:30
本文介绍了位图 getWidth 返回错误值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 android 应用程序可绘制文件夹中有一个 jpg 图像,分辨率为 1000x600.我像这样将该图像加载到位图

 Bitmap bitMap = BitmapFactory.decodeResource(getResources(), R.drawable.image);

在此之后我调用 bitMap .getWidth() 返回 1500.它怎么可能?以及如何获得正确的图像宽度和高度?

解决方案

这可能是因为密度不同.您的资源可能存储在中等密度的文件夹中,但您的设备是 hdpi.中密度为 160dpi,高密度为 240dpi.因此,您的位图被缩放到原来大小的 1.5 倍.有关详细信息,请参阅多屏幕文档.

<块引用>

如果资源在正确的密度下不可用,系统会加载默认资源并根据需要放大或缩小它们以匹配当前屏幕的密度.

如果您打算将其用于高密度,请将其放入 drawable-hdpi 而不是 drawable 或 drawable-mdpi.

更新:

如果你想让它忽略密度,把它放在一个 drawable-nodpi 文件夹中.同样来自同一个文档:

<块引用>

避免预缩放的最简单方法是将资源放在带有 nodpi 配置限定符的资源目录中.例如:

res/drawable-nodpi/icon.png

<块引用>

当系统使用此文件夹中的 icon.png 位图时,它不会根据当前设备密度对其进行缩放.

I have a jpg image in my android application drawable folder which resolution is 1000x600. I load that image to bitmap like this

 Bitmap bitMap = BitmapFactory.decodeResource(getResources(), R.drawable.image);

After this I call bitMap .getWidth() which returns 1500. How it can be? And how to get the right width and height of image?

解决方案

This is probably because of differing densities. Your resource is probably stored in a medium density folder, but your device is hdpi. Medium density is 160dpi, high density is 240dpi. Thus your bitmap is scaled to 1.5x the size it was originally. See the document on multiple screens for more info.

If resources are not available in the correct density, the system loads the default resources and scales them up or down as needed to match the current screen's density.

If you intended this to be for high density put it in drawable-hdpi instead of drawable or drawable-mdpi.

Update:

If you want it to ignore density, put it in a drawable-nodpi folder. Also from the same doc:

The easiest way to avoid pre-scaling is to put the resource in a resource directory with the nodpi configuration qualifier. For example:

res/drawable-nodpi/icon.png

When the system uses the icon.png bitmap from this folder, it does not scale it based on the current device density.

这篇关于位图 getWidth 返回错误值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆