简体   繁体   中英

How to Save the drawing canvas in android?

I am using this API demo of the Developer site, THIS DEMO.

But i am wonder that how to save that image in to My Andrtoid Device. Is please anyone give the Code to save that drawn image to the Android Device.

Thanks.

try this code

View content = your_view;
content.setDrawingCacheEnabled(true);
content.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Bitmap bitmap = content.getDrawingCache();
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File(path+"/image.png");
FileOutputStream ostream;
try {
    file.createNewFile();
    ostream = new FileOutputStream(file);
    bitmap.compress(CompressFormat.PNG, 100, ostream);
    ostream.flush();
    ostream.close();
    Toast.makeText(getApplicationContext(), "image saved", 5000).show();
} catch (Exception e) {
    e.printStackTrace();
    Toast.makeText(getApplicationContext(), "error", 5000).show();
}
drawView.setDrawingCacheEnabled(true);
Bitmap bm = null;
drawView.destroyDrawingCache();
bm=drawView.getDrawingCache();

Then write the bitmap to file using bitmap factory.

I have implemented the below approach & worked for me. Get your CustomView by using its id from xml file but not by instantiating the Customview.

 View v = findViewById(R.id.custom_view); //don't get customview by this way, View v = new CustomView(this); int canvasWidth = v.getWidth(); int canvasHeight = v.getHeight(); Bitmap bitmap = Bitmap.createBitmap(canvasWidth, canvasHeight, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); v.draw(canvas); ImageView imageView = findViewById(R.id.image_view); imageView.setImageBitmap(bitmap);

All code should be inside saveButton click listener.

One option is create another Canvas (as shown below) and repeat all your drawing on this new canvas. Once done, call drawBitmap.

Bitmap bitmap = new Bitmap(// Set the params you like //);
Canvas canvas = new Canvas(bitmap);

// Do all your drawings here

canvas.drawBitmap(// The first picture //);

The best would be if there was a way to copy an existing canvas and then you wont need to re-draw everything but I couldn't find one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM