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”文字。

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

canvas.drawPicture(mPicture);

重新指定Picture的绘制区域,实现对Picture的缩放。

canvas.drawPicture(mPicture, new RectF(0, 100, getWidth(), 200));


使用PictureDrawable


mDrawable = new PictureDrawable(mPicture);
 
mDrawable.setBounds(0, 200, getWidth(), 300);
mDrawable.draw(canvas);


将Picture写道一个Stream中,然后再从Stream中恢复这个Picture

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值