Android ApiDemos示例解析(72):Graphics->Pictures
从功能上看android.graphics.Picture 和 android.graphics.Bitmap 非常像。 Picture可以记录在Canvas上每个绘制操作(通过beginRecording返回的Canvas),然后回放每个绘图操作。同时也支持将Picture中的内容写到Stream中,并支持从Stream恢复Picture。这些功能使用Bitmap也能实现。但Picture 只是记录绘图操作而不是绘制后的像素结果,因此存储大小比同样大小的Bitmap要小得多,本例Picture写到Stream的大小为385个字节。而对于的绘图区域为200X100,如以RGB888格式则需要80000字节。没有仔细研究Picture的内部格式,举个类似的例子,Picture可能存储类似SVG的指令(绘图操作)而非渲染之后的结果。
除了存储空间小之外,根据Android文档,使用Picture存取绘图操作然后回放到屏幕的操作比直接再使用同样的绘图操作在屏幕上渲染的速度要快的多。
从Picture获取可以绘图用的Canvas的方法为
public CanvasbeginRecording(int width, int height)
其中width, height 指定了Canvas的宽度和长度。
本例创建一个Picture对象,并在其上记录一个粉色圆和”Picture”文字。
[java] view plaincopyprint?
mPicture = new Picture();
drawSomething(mPicture.beginRecording(200, 100));
mPicture.endRecording();
...
static void drawSomething(Canvas canvas) {
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setColor(0x88FF0000);
canvas.drawCircle(50, 50, 40, p);
p.setColor(Color.GREEN);
p.setTextSize(30);
canvas.drawText("Pictures", 60, 60, p);
}
mPicture = new Picture();
drawSomething(mPicture.beginRecording(200, 100));
mPicture.endRecording();
...
static void drawSomething(Canvas canvas) {
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setColor(0x88FF0000);
canvas.drawCircle(50, 50, 40, p);
p.setColor(Color.GREEN);
p.setTextSize(30);
canvas.drawText("Pictures", 60, 60, p);
}然后使用多种方法来“回放”这个Picture 到屏幕上。
直接绘制Picture
[java]
canvas.drawPicture(mPicture);
canvas.drawPicture(mPicture);重新指定Picture的绘制区域,实现对Picture的缩放。
[java]
canvas.drawPicture(mPicture, new RectF(0, 100, getWidth(), 200));
canvas.drawPicture(mPicture, new RectF(0, 100, getWidth(), 200));
使用PictureDrawable
[java]
mDrawable = new PictureDrawable(mPicture);
mDrawable.setBounds(0, 200, getWidth(), 300);
mDrawable.draw(canvas);
mDrawable = new PictureDrawable(mPicture);
mDrawable.setBounds(0, 200, getWidth(), 300);
mDrawable.draw(canvas);
将Picture写道一个Stream中,然后再从Stream中恢复这个Picture
[java]
ByteArrayOutputStream os = new ByteArrayOutputStream();
mPicture.writeToStream(os);
System.out.println("ByteArrayOutputStream:"+os.size());
InputStream is = new ByteArrayInputStream(os.toByteArray());
canvas.translate(0, 300);
canvas.drawPicture(Picture.createFromStream(is));
ByteArrayOutputStream os = new ByteArrayOutputStream();
mPicture.writeToStream(os);
System.out.println("ByteArrayOutputStream:"+os.size());
InputStream is = new ByteArrayInputStream(os.toByteArray());
canvas.translate(0, 300);
canvas.drawPicture(Picture.createFromStream(is));
作者:mapdigit
补充:移动开发 , Android ,