安卓ondraw刷新视图_安卓View.onDraw()总是有一个干净的画布

I am trying to draw an animation. To do so I have extended View and overridden the onDraw() method. What I would expect is that each time onDraw() is called the canvas would be in the state that I left it in and I could choose to clear it or just draw over parts of it (This is how it worked when I used a SurfaceView) but each time the canvas comes back already cleared. Is there a way that I can not have it cleared? Or maybe save the previous state into a Bitmap so I can just draw that Bitmap and then draw over top of it?

解决方案

I'm not sure if there is a way or not. But for my custom views I either redraw everything each time onDraw() is called, or draw to a bitmap and then draw the bitmap to the canvas (like you suggested in your question).

Here is how i do it

class A extends View {

private Canvas canvas;

private Bitmap bitmap;

protected void onSizeChanged(int w, int h, int oldw, int oldh) {

if (bitmap != null) {

bitmap .recycle();

}

canvas= new Canvas();

bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);

canvas.setBitmap(bitmap);

}

public void destroy() {

if (bitmap != null) {

bitmap.recycle();

}

}

public void onDraw(Canvas c) {

//draw onto the canvas if needed (maybe only the parts of animation that changed)

canvas.drawRect(0,0,10,10,paint);

//draw the bitmap to the real canvas c

c.drawBitmap(bitmap,

new Rect(0,0,bitmap.getWidth(),bitmap.getHeight()),

new Rect(0,0,bitmap.getWidth(),bitmap.getHeight()), null);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值