开发者

How to draw game on Android Canvas with lots of primitives

开发者 https://www.devze.com 2023-01-26 22:23 出处:网络
I draw a lot of lines rectangles each frame in my game - it\'s a recreation of an old school 开发者_JAVA百科handheld electronic game. The ones that had crude dot matrix display for the main game and c

I draw a lot of lines rectangles each frame in my game - it's a recreation of an old school 开发者_JAVA百科handheld electronic game. The ones that had crude dot matrix display for the main game and custom images for text or some images.

I have 20x20 big "pixels" on a virtual dot matrix screen, I also draw some 7-segment displays on the screen and some other things.

According to TraceView, most of time is spent at drawLine and drawRectangle methods, because there is simply too much of them. I draw each 'pixel' of the dot matrix display, and each segment of 7-segment displays in every frame.

An optimization came to my mind, that I would repaint only those pixels/segments which changed, so I have saved the previous state of pixels/segments and tried to repaint only changed ones. Basically it's a crude invalidation.

The behavior I was expecting was that the Canvas would stay as it was after the last frame finished painting, and I would only repaint necessary stuff.

Alas, my Canvas was flickering to black and every once in a while when state of my screen changed, only pixels of dot matrix display/segments flickered on for a frame. And I made sure that I didn't Clear my canvas.

I'm drawing on a Canvas inside a SurfaceView, updating Thread, as is described in Lunar Lander Android sample. In the Lunar Lander sample, they repaint everything in each frame.

Maybe I could render everything to a Bitmap on the first frame, then update that Bitmap on every other frame?

Which technique should I use for my paint() method?


SurfaceHolder.unlockCanvasAndPost() actually does page flipping on the Surface, so even if the previous frame wasn't cleared out you'd get the 2nd oldest frame, not the one you just drew. and doing lock() on a surface instantiates a new canvas each time which probably is doing the clearing in its constructor.

You're better off drawing into a Bitmap like someone suggested and then drawBitmap on the canvas each time you want to present the image to the display. You can aquire a canvas from a bitmap to draw into it

and like someone else suggested (very ambiguously), you can generate sprites for the dot matrix display and draw those directly from a cache of bitmaps rather then draw with primitive commands. ie for a dot matrix calculator you could generate all 0-9 into 10 bitmaps and simply blit them on the canvas rather then calling a set of drawLine/Rect operations.

if the above are still too slow there still is opengl, which takes advantage of hardware acceleration


Why not to go for Sprites?

0

精彩评论

暂无评论...
验证码 换一张
取 消