0

我的应用程序是某种“迷你绘画”,我想将当前视图保存到设备内存中......我也想做相反的过程(从设备内存中加载图像并将其设置为我的当前视图)

迷你油漆

是的,那应该是火烈鸟,我是艺术家!

4

2 回答 2

2

我自己没有尝试过,但这个答案显示通过获取根视图并保存其绘图缓存以编程方式截取屏幕截图。这可能是您保存画作所需的全部内容。

编辑:固定链接

于 2012-01-23T03:58:09.910 回答
1

首先,我假设您通过覆盖 View 对象上的 onDraw() 方法来执行此绘图,该方法传入一个 Canvas 对象,然后您可以在该对象上执行一些绘图操作。

这是解决此问题的一种非常基本的方法。可能还有许多额外的考虑因素需要考虑,例如您读取和写入的文件格式,以及 I/O 代码中的一些额外错误处理。但这应该让你继续前进。

要保存您当前拥有的绘图,请将 View 的 drawingCache 写入 Picture 对象,然后使用 Picture 的 writeToStream 方法。

要加载预先存在的图片,可以使用 Picture.readFromStream 方法,然后在 onDraw 调用中,将加载的图片绘制到 Canvas。

以机智:

/**
 * Saves the current drawing cache of this View object to external storage.
 * @param filename a file to be created in the device's Picture directory on the SD card
 */
public void SaveImage(String filename) {
    // Grab a bitmap of what you've drawn to this View object so far
    Bitmap b = this.getDrawingCache();
    // It's easy to save a Picture object to disk, so we copy the contents
    // of the Bitmap into a Picture
    Picture pictureToSave = new Picture();
    // To copy the Bitmap into the Picture, we have to use a Canvas
    Canvas c = pictureToSave.beginRecording(b.getWidth(), b.getHeight());
    c.drawBitmap(b, 0, 0, new Paint());
    pictureToSave.endRecording();

    // Create a File object where we are going to write the Picture to
    File file = new File(this.getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES), filename);
    try {
        file.createNewFile();
    }
    catch (IOException ioe) {
        ioe.printStackTrace();
    }
    // Write the contents of the Picture object to disk
    try {
        OutputStream os = new FileOutputStream(file);
        pictureToSave.writeToStream(os);
        os.close();
    }
    catch (FileNotFoundException fnfe) {
        fnfe.printStackTrace();
    }
}

/**
 * Returns a Picture object loaded from external storage
 * @param filename the name of the file in the Pictures directory on the SD card
 * @return null if the file is not found, or a Picture object.
 */
public Picture LoadImage(String filename) {
    // Load a File object where we are going to read the Picture from
    File file = new File(this.getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES), filename);
    Picture pictureToLoad = null;
    try {
        InputStream is = new FileInputStream(file);
        pictureToLoad = Picture.createFromStream(is);
        is.close();
    }
    catch (FileNotFoundException fnfe) {
        fnfe.printStackTrace();
    }
    // Return the picture we just loaded. Draw the picture to canvas using the
    // Canvas.draw(Picture) method in your View.onDraw(Canvas) method
    return pictureToLoad;
}

我阅读了有用的链接来解决这个问题:

于 2012-01-23T04:57:23.373 回答