我的应用程序是某种“迷你颜料”,我想将当前视图保存到设备内存中...我也想做相反的过程(从设备内存加载图像并设置它作为我的当前观点)
是的,我想这是一个火烈鸟,我是一个艺术家!答案 0 :(得分:2)
我自己没有尝试过,但this answer显示通过获取根视图并保存其绘图缓存来以编程方式截取屏幕截图。这可能是您保存绘画所需的全部内容。
编辑:固定链接
答案 1 :(得分: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;
}
我读到的有用链接可以解决这个问题: