IllegalArgumentException: x + width must be <= bitmap.width() in android

喜欢而已 提交于 2020-01-15 11:57:11

问题


I want to crop an image with in a margin (10,50,10,50),(left,top,right,bottom) respectively of an imageview. Here is my code

Bitmap bitmap = Bitmap.createBitmap(imgView.getWidth(),imgView.getHeight(), Bitmap.Config.ARGB_8888);

Bitmap result = Bitmap.createBitmap(bitmap, (imgView.getLeft() + 10),
                imgView.getTop() + 50,imgView.getRight() - 10,imgView.getBottom() - 50);
bitmap.recycle();
Canvas canvas = new Canvas(result);
imgView.draw(canvas);

ie, if my imageview is of dimension 200X300.then i want to get the bitmap image with in the specified area only .When I am trying to do this It shows error

 FATAL EXCEPTION: main
 java.lang.IllegalArgumentException: x + width must be <= bitmap.width()
    at android.graphics.Bitmap.createBitmap(Bitmap.java:410)
    at android.graphics.Bitmap.createBitmap(Bitmap.java:383)
    at android.view.View.performClick(View.java:2485)
    at android.view.View$PerformClick.run(View.java:9080)
    at android.os.Handler.handleCallback(Handler.java:587)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:130)
    at android.app.ActivityThread.main(ActivityThread.java:3687)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:507)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
    at dalvik.system.NativeStart.main(Native Method)

How can i solve this?

Thanks


回答1:


try this and see if it works:

// using this method createBitmap(source, x, y, width, height)
Bitmap result = Bitmap.createBitmap(bitmap, 10,
            50, imgView.getWidth() - 20, imgView.getHeight() - 100);

getLeft and others is used to get the position of the view in its parent. Not the dimension of the bitmap.




回答2:


    Bitmap resultBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0,
            sourceBitmap.getWidth() - 1, sourceBitmap.getHeight() - 1);

Like in lists, it starts from 0, so width must be bitmap width - 1.



来源:https://stackoverflow.com/questions/12852968/illegalargumentexception-x-width-must-be-bitmap-width-in-android

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