【发布时间】:2013-11-23 10:47:27
【问题描述】:
Google 建议从缩小的资源中加载位图,具体取决于实际的 ImageView 大小(Google 开发人员指南中的“有效加载大型位图”)。因此,在解码位图之前,我必须知道 ImageView 的宽度和高度。
我的代码类似于下面发布的代码。 decodeSampledBitmapFromResources 将位图作为存储在资源中的位图的缩小版本返回。
public void onCreate(Bundle savedInstanceSate)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.myLayout)
ImageView imageView = (ImageView) findViewById(R.id.myImageView);
/**
At this point, I need to calculate width and height of the ImageView.
**/
Bitmap bitmap = MyBitmapManager.decodeSampledBitmapFromResource(
getResources(), R.drawable.my_icon, width, height);
imageView.setImageBitmap(bitmap);
}
问题是,当我在 onCreate 中时,我的 ImageView 还没有任何宽度和高度。 getWidth() 和 getHeight() 只是返回 0。我偶然发现了这段代码,以便在实际绘制视图之前计算它的大小:
ImageView v = findViewById(R.id.myImageView);
v.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int width = v.getMeasuredWidth();
int height = v.getMeasuredHeight();
这适合我的情况吗?我试过了,上面的代码返回了一些似乎是正确的宽度和高度值,但我不确定这是否是正确的方法。
更新: 经过更多测试,这似乎不起作用。 在上面的示例中,我使用了大小为 192x192 像素的 PNG。 如上所示测量 ImageView 后,我得到的测量尺寸为 128x128。 如果我在位图设置为图像视图后调用 getWidth() 和 getHeight(),则尺寸为 100x100。 因此,在这种情况下,图像会从 192x192 缩小到 128x128,但不会缩小到应有的 100x100。
似乎Measurespec.UNSPECIFIED 总是返回大于它们最后的尺寸。
提前致谢,
丹珠
【问题讨论】:
标签: java android user-interface bitmap imageview