如何在Android中保存绘图画布?

7
我正在使用开发者网站上的API演示,这个演示。 但我想知道如何将图像保存到我的安卓设备中。请问是否有任何代码可以将绘制的图像保存到安卓设备中?
谢谢。

1
请访问以下链接以获取答案:链接 - Lucifer
4个回答

13

试试这段代码

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();
}

1
我该如何保存view的背景?目前只能保存绘图,但无法保存背景。 - Si8
答案说View content = you_view; 我错了吗?我应该放置我的布局ID还是视图ID?我做了这个View content = findViewById(R.id.content); 然后我得到了“尝试在空对象引用上调用虚拟方法'void android.view.View.setDrawingCacheEnabled(boolean)'” - makkhay gurung

1
drawView.setDrawingCacheEnabled(true);
Bitmap bm = null;
drawView.destroyDrawingCache();
bm=drawView.getDrawingCache();

然后使用位图工厂将位图写入文件。


0

一种选择是创建另一个画布(如下所示),并在这个新画布上重复所有的绘制。完成后,调用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 //);

最好的方法是能够复制现有的画布,这样就不需要重新绘制所有的内容了,但我找不到这个功能。

0
我已经实现了以下方法,对我很有效。 通过从XML文件中使用其ID获取CustomView,而不是实例化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);

所有代码都应该放在saveButton的点击事件监听器中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接