【问题标题】:How to Save the drawing canvas in android?如何在android中保存绘图画布?
【发布时间】:2012-01-01 00:27:14
【问题描述】:

我正在使用开发者网站的这个 API 演示,THIS DEMO.

但我想知道如何将该图像保存到我的 Andrtoid 设备中。 请任何人提供代码以将该绘制的图像保存到 Android 设备。

谢谢。

【问题讨论】:

标签: android android-layout android-emulator android-widget android-canvas


【解决方案1】:

试试这个代码

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

【讨论】:

  • 如何保存view的背景?现在只保存绘图而不保存背景。
  • 答案说 View content = you_view;纠正我如果我错了,我应该输入我的布局 ID 还是视图 ID?我做了这个 View content = findViewById(R.id.content);我得到“尝试在空对象引用上调用虚拟方法'void android.view.View.setDrawingCacheEnabled(boolean)'”
【解决方案2】:
drawView.setDrawingCacheEnabled(true);
Bitmap bm = null;
drawView.destroyDrawingCache();
bm=drawView.getDrawingCache();

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

【讨论】:

    【解决方案3】:

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

    如果有一种方法可以复制现有的画布,那么最好的办法是您不需要重新绘制所有内容,但我找不到。

    【讨论】:

      【解决方案4】:

      我已经实施了以下方法并为我工作。 通过使用 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 点击​​监听器中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-12
        • 2012-09-13
        相关资源
        最近更新 更多