首页 文章

Android Imageview:未指定测量以计算位图尺寸

提问于
浏览
0

谷歌建议从按比例缩小的资源加载位图,具体取决于实际的ImageView大小(googles开发人员指南中的“有效加载大位图”) . 因此,在解码位图之前,我必须知道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();

这适合我的情况吗?我试过了,上面的代码返回了宽度和高度的一些值似乎是正确的,但我不确定这是否是正确的方法 .

UPDATE: 经过多次测试后,这似乎无法奏效 . 在上面的示例中,我使用大小为192x192像素的PNG . 在如上所示测量ImageView之后,我得到128x128的测量尺寸 . 如果在将位图设置为imageview之后调用getWidth()和getHeight(),则尺寸为100x100 . 所以在这种情况下,图像从192x192缩小到128x128,但不是100x100 .

似乎 Measurespec.UNSPECIFIED 总是返回大于它们最后的尺寸 .

提前致谢,

danijoo

1 回答

  • 0

    我自己解决了这个问题:

    ViewTreeObserver vto = imageView.getViewTreeObserver();
    vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        public boolean onPreDraw(){
            // at this point, true width and height are already determined
            int width = imageView.getMeasuredWidth();
            int height = imageView.getMeasuredHeight();
    
            Bitmap bitmap = MyBitmapManager.decodeSampledBitmapFromResource(
                            getResources(), R.drawable.my_icon, width, height);
            imageView.setImageBitmap(bitmap);
    
            // this is important because onPreDrawn is fired multiple times
            imageView.getViewTreeObserver().removeOnPreDrawListener(this);
            return true;
        }
    }
    

相关问题