Simplifying a bit, I have a custom control that draws an LED bargraph sound level meter at 20 frames per second (as data is received). My current implementation works okay, but with 16 controls on the screen it consumes too much CPU on older machines... I know it can be better.
Currently I'm overriding onDraw() to draw the following layers in order:
- A cached background bitmap that doesn't change
- An arrow in a variable position with e.Graphics.DrawImageUnscaled()
- e.Graphics.FillRectangle() to fill Green/Yellow/Red based on data
- e.Graphics.DrawString() to draw value at the top
Here's a mockup of the final product:
Is this the best way to do that? I could conceivably pre-render everything into bitmaps and simply clip them as needed... and maybe still use DrawString for the number(?)... but what is the best approach? Should I even be doing that in onDraw()? Graphics functions in c# are not my strongest area.
Thank you for any advice you can provide.
Edit: Sounds like I'm doing about as good as WinForms will do and it's actually doing just fine. On my development machine it's taking just 0.32ms to paint the control. I'm reacting to a complaint of 100% CPU usage and dropped frames, but the customer is using 10-year-old hardware and I suspect the graphics adapter is not great.
Still, this post was very helpful for general improvements, and did shave a few microseconds off my painting time: