1

I am a newbie. I make a simple game using Canvas. I wrote almost all the code inside the onDraw() method and there is a lot of calculations there. There is an invalidate() method in the end of onDraw() in my code. That's how I call to redraw my view. How can I redraw only a part of Canvas? The main problem is that I have a lot of calculations inside the onDraw() and it slows the whole game. I tried to use bitmaps like here:

creating a bitmap - stackOverflow

but it didn't resolve the problem because creating a bitmap is too slow process. Is it a good idea to use SurfaceHolder and Callback? I tried to use it but I don't know if it is a right way to do what I want to do. Can anybody help me? How to redraw my view only partially to stop chosen elements always redrawing by new calculations (to drawing them from saved state)? I want to redraw whole view only when it is needed. It would be great if somebody post a code which would resolve this problem (it could be even two rectangles).

Community
  • 1
  • 1
  • First of all you should not do heavy calculations or memory allocation within `onDraw`. They have to be done before invalidate will be invoked. You could add a new thread that does those calculations. And after they done invoke postInvalidate();. And do not invoke `onDraw` by yourself, `invalidate` or `postInvalidate` does it on its own. – Bob Oct 20 '16 at 12:16

2 Answers2

1

use the same bitmap instead of creating a new one, and call invalidate with a rectangle (or with the bounds) as its parameter.

in the onDraw, you can call canvas.getClipBounds() in order to find the rectangle to invlidate.

also, in order to improve your code, try to avoid creating new objects on the onDraw method.

in fact, if it's a heavy game, consider using openGL instead. for simplicity, you can use third party libraries like libGDX or AndEngine.

android developer
  • 114,585
  • 152
  • 739
  • 1,270
1

Try creating the Bitmaps in the Class method and calling them from onDraw().

   public class DrawView extends View {

         public DrawView(Context context, AttributeSet attributeSet) {
         super.DrawView(context attributeSet)
          //Create your bitmaps in here
         }
   }
Caleb Bramwell
  • 1,332
  • 2
  • 12
  • 24