Android的:如何获得自定义视图重绘部分? [英] Android: How to get a custom view to redraw partially?

查看:769
本文介绍了Android的:如何获得自定义视图重绘部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个充满了我的整个屏幕自定义视图。 (钢琴键盘) 当用户触摸键时,它会导致无效()被称为与全键盘被重新绘制以显示新的状态触摸键。

I have a custom view that fills my entire screen. (A piano keyboard) When a user touches the key, it causes invalidate() to be called and the whole keyboard gets redrawn to show the new state with a touched key.

目前的看法很简单,但我计划增加多一点漂亮的图形。由于整个键盘动态呈现,这将使得重画整个键盘更加昂贵。

Currently the view is very simple, but I plan to add a bit more nice graphics. Since the whole keyboard is dynamically rendered this would make redrawing the entire keyboard more expensive.

所以我想,让我们看看部分重绘。现在,我称之为无效(矩形脏)用正确的脏区。我把我的的OnDraw(帆布油画)法中之荤地区唯一绘制键,如果我确实想要部分重绘。这导致这些键被绘制,但键盘的其他部分完全是黑色/未拉伸的。

So I thought, let's look into partial redrawing. Now I call invalidate(Rect dirty) with the correct dirty region. I set my onDraw(Canvas canvas) method to only draw the keys in the dirty region if I do indeed want a partial redraw. This results in those keys being drawn, but the rest of the keyboard is totally black/not drawn at all.

我是错误的期待,调用无效(矩形脏)将缓存的电流画布,和只有允许图中的脏区?

Am I wrong in expecting that calling invalidate(Rect dirty) would "cache" the current canvas, and only "allows" drawing in the dirty region?

有没有什么办法可以达到我想要的吗? (一办法缓存的画布,只有重绘脏区?

Is there any way I can achieve what I want? (A way to "cache" the canvas and only redraw the dirty area?"

推荐答案

目前不错的解决方法是手动缓存满画布为位图:

Current nice workaround is to manually cache the full canvas to a bitmap:

 private void onDraw(Canvas canvas)
 {
     if (!initialDrawingIsPerformed)
     {
          this.cachedBitmap = Bitmap.createBitmap(getWidth(), getHeight(),
            Config.ARGB_8888); //Change to lower bitmap config if possible.
          Canvas cacheCanvas = new Canvas(this.cachedBitmap);
          doInitialDrawing(cacheCanvas);
          canvas.drawBitmap(this.cachedBitmap, 0, 0, new Paint());
          initialDrawingIsPerformed = true;
     }
     else
     {
          canvas.drawBitmap(this.cachedBitmap, 0, 0, new Paint());
          doPartialRedraws(canvas);
     }
 }

Ofcourse,你需要存储哪些重绘自己和preferably不会使用新的油漆每次的信息,但都是一些细节。

Ofcourse, you need to store the info about what to redraw yourself and preferably not use a new Paint everytime, but that are details.

另外请注意:位图是在您的应用程序的内存使用量相当繁重。我有崩溃的时候我缓存这是一个滚动使用的视图,而且是像设备的5倍的高度,因为它使用> 10MB内存!

Also note: Bitmaps are quite heavy on the memory usage of your app. I had crashes when I cached a View that was used with a scroller and that was like 5 times the height of the device, since it used > 10MB memory!

这篇关于Android的:如何获得自定义视图重绘部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆