问题
I am using following code
public void cropSelection(){
Bitmap bitmap = annotationBitmap.copy(annotationBitmap.getConfig(), true);
Canvas canvas = new Canvas(bitmap);
Paint p = new Paint();
// p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.XOR));
canvas.drawBitmap(imageBitmap, 0, 0, p); // this line throws error
imageBitmap = bitmap;
}
More surprisingly when I am using the same line canvas.drawBitmap(imageBitmap, 0, 0, p)
inside onDraw()
it does not throw any error. It works well.
Stacktrace
2020-01-17 11:20:07.815 21388-21388/com.mayank.picturemagic E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mayank.picturemagic, PID: 21388
java.lang.IllegalArgumentException: Software rendering doesn't support hardware bitmaps
at android.graphics.BaseCanvas.onHwBitmapInSwMode(BaseCanvas.java:550)
at android.graphics.BaseCanvas.throwIfHwBitmapInSwMode(BaseCanvas.java:557)
at android.graphics.BaseCanvas.throwIfCannotDraw(BaseCanvas.java:69)
at android.graphics.BaseCanvas.drawBitmap(BaseCanvas.java:109)
at android.graphics.Canvas.drawBitmap(Canvas.java:1456)
at com.mayank.picturemagic.MainView.cropSelection(MainView.java:434)
at com.mayank.picturemagic.k$6.onClick(k.java:330)
at android.view.View.performClick(View.java:6608)
at android.view.View.performClickInternal(View.java:6585)
at android.view.View.access$3100(View.java:785)
at android.view.View$PerformClick.run(View.java:25921)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
回答1:
Finally got a pretty solution
imageBitmap = imageBitmap.copy(Bitmap.Config.ARGB_8888, true);
Essentially removing the HARDWARE config from the bitmap.
To get around this problem, earlier I was trying imageBitmap = imageBitmap.copy(imageBitmap.getConfig(), true);
In this case the the config is HARDWARE and it throws error hardware bitmaps are always immutable.
However there should be more efficient solution and also the part of the question - why this works inside onDraw() but not outside remains
来源:https://stackoverflow.com/questions/59781937/trying-to-crop-bitmap-using-mask-throws-illegalargumentexception