IllegalArgumentException: width and height must be > 0 while loading Bitmap from View

一世执手 提交于 2019-11-26 22:48:46

I finally figured out a solution for my problem.

I'm using the post method of the View, which will be executed only after the view measuring and layouting, this way getWidth() and getHeight() returns the actual width and height.

Here's the code sample:

mImage.post(new Runnable() {
    @Override
    public void run() {
        mImage.setImageBitmap(loadBitmapFromView(mImage));
    }
});

Hope it also helps someone else :)

If everything else is correct you are executing your code too early.

The view's layout has not yet been measured by Android. Try executing in OnResume just to see if this is your problem.

Cheers!

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            loadBitmapFromView(mImage);
        }
    }, 1000);

java.lang.IllegalArgumentException: width and height must be > 0 is because in your Bitmap.createBitmap() call v.getLayoutParams().width or v.getLayoutParams().height is 0. Probably the LayoutParams are wrongly set in mImage.

Update: setLayoutParams() for the mImage before using createBitmap(). Something like this:

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
mImage.setLayoutParams(layoutParams);

In my case, I forgot to set orientation to vertical for parent LinearLayout and the default value of horizontal has been set, so I set it and my problem gone...

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