开发者

Drawing to the canvas

开发者 https://www.devze.com 2022-12-23 21:20 出处:网络
I\'m writing an android application that draws directly to the canvas on the onDraw event of a View. I\'m drawing something that involves drawing each pixel individually, for this I use something lik

I'm writing an android application that draws directly to the canvas on the onDraw event of a View.

I'm drawing something that involves drawing each pixel individually, for this I use something like:

for (int x = 0; x < xMax; x++) {
  for (int y = 0; y < yMax; y++){
    MyColour = CalculateMyPoint(x, y);
    canvas.drawPoint(x, y, MyColour);
  }
}

The problem here is that this takes a 开发者_StackOverflowlong time to paint as the CalculateMyPoint routine is quite an expensive method.

Is there a more efficient way of painting to the canvas, for example should I draw to a bitmap and then paint the whole bitmap to the canvas on the onDraw event? Or maybe evaluate my colours and fill in an array that the onDraw method can use to paint the canvas?

Users of my application will be able to change parameters that affect the drawing on the canvas. This is incredibly slow at the moment.


As people have pointed out, if CalculateMyPixel() is expensive, having that called 150,000 (HVGA) or 384,00 times (WVGA) is just going to kill you.

On top of that, trying to draw your UI as individual pixels via canvas.drawPoint() each time there is an update is just about the least efficient way to do this.

If you are drawing individual pixels, you almost certainly want to have some kind of off-screen bitmap containing the pixels, which you draw with a simple Canvas.drawBitmap().

Then you can decide the best way to manage that bitmap. This simplest is to just make a Bitmap object of the desired size and use the APIs there to fill it in.

Alternatively, there is a version of drawBitmap() that takes a raw integer array, so you can fill that in directly with whatever values you want, avoiding a method call for each pixel.

Now you can move your pixel calculation out of the onDraw() method, which needs to be fast to have a responsive UI, and fill your pixels in somewhere else. Maybe you compute them once at initialization time. Maybe you compute them, and do selective updates of only the parts that have changed before calling invalidate() (for example the pixels from (0,0)-(10,l0) have changed so take the current bitmap and just modify that area). If computing pixels is really just intrinsically slow, you will probably want to create a separate thread to do that work in (updating the bitmap with the new pixels, then postInvalidate() on the UI to get them drawn).

Also now that you have your pixels in a bitmap, you can do tricks like make the size of the bitmap smaller and scale it when drawing to the screen, allowing you to take much less time updating those pixels while still filling the entire UI (albeit at a lower resolution).

0

精彩评论

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