将画布保存为jpeg,而画布不可见

时间:2013-06-28 04:08:07

标签: android android-canvas

我使用用户输入的数据以编程方式绘制到画布。输入所有数据后,用户可以翻阅图像并将它们绘制到画布上。用户可以选择保存所有图像(可能是几百个)。我使用在UI线程上运行的runnable将绘制并保存每个图像(因为您无法从AsyncTask绘制到画布)。这有效,但我遇到的问题是,如果正在进行保存,用户将关闭屏幕或最小化应用程序。这导致jpegs只是黑色。我希望保存能够在后台运行,并且仍能正常工作。

用于绘制到画布并保存图像的代码:

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    Bitmap bitmap;
    bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    canvas.setBitmap(bitmap);

    // draw everything here

    OutputStream stream = new FileOutputStream(imageName + ".jpg");
    bitmap.compress(CompressFormat.JPEG, 100, stream);
    stream.close();
}

那么,当画布不可见时,有没有办法将图像绘制并保存到背景中的文件中?任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:-1)

I think you can use this:

signLayout.setDrawingCacheEnabled(true); //signLayout is layout that contains image you want to save
    // Save image from layout
    String path = "sdcard0/test/test.jpg"; //file path you want to save
    gestureSign.save(signLayout, path);

保存方法

//Save to path
public void save(View v, String SavePath) 
{
    if(mBitmap == null)
    {
        mBitmap =  Bitmap.createBitmap (layoutSign.getWidth(), layoutSign.getHeight(), Bitmap.Config.RGB_565);;
    }
    Canvas canvas = new Canvas(mBitmap);
    try
    {
        FileOutputStream mFileOutStream = new FileOutputStream(SavePath);
        v.draw(canvas); //Lay toan bo layout
        mBitmap.compress(Bitmap.CompressFormat.PNG, 100, mFileOutStream); 
        mFileOutStream.flush();
        mFileOutStream.close();
    }
    catch(Exception e) 
    { 
        Log.v("log_tag", e.toString()); 
    } 
}