i want to convert canvas to image and save it on device. But when I set bitmap to canvas I get error java.lang.UnsupportedOperationException.
My full code:
public class SingleTouchEventView extends View {
private Paint paint = new Paint();
private Path path = new Path();
public SingleTouchEventView(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(6f);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.BEVEL);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
canvas.drawCircle(50, 50, 3, paint);
Bitmap bitmap = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Bitmap.Config.ARGB_8888);
canvas.setBitmap(bitmap);
try {
File file = new File(Environment.getExternalStorageDirectory() + "/image.jpg");
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Maybe someone could help me to solve this problem?
That isn't how you draw to a bitmap. You do NOT use the canvas that draws to the screen. You create a second canvas, passing in the bitmap you want to draw to as a parameter in the constructor. Then any draw commands to that canvas will draw the bitmap. Then you draw that bitmap to the screen. Something like this:
Canvas myCanvas = new Canvas(myBitmap);
myCanvas.drawLine();
myCanvas.drawCircle();
//Insert all the rest of the drawing commands here
screenCanvas.drawBitmap(myBitmap, 0, 0);
I also would not write it to the file system in onDraw - I'd expect drawing performance to suffer badly if you do. A separate function call can do that. If you keep myBitmap around in a variable, you can just compress it anytime to write out the last draw to disk.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With