Search code examples
javaandroidandroid-canvasandroid-drawable

How to partially redraw a non-rect shaped part of the canvas


I'm make a custom line chart view in android and I'm trying to implement a sort of drag/scroll function that drags a small circle across the x axis depending on where you are touching the screen.

I'm wondering if there is a way to redraw only this circle on each onTouchEvent call. (the circle is a Drawable btw). i know i can invalidate a portion of the canvas with invalidate(Rect dirty) but it looks like its deprecated now and wouldn't work anyway because i need the background layer (the lines and grid) to remain

Alternatively, I could just redraw the entire chart on each event... is that considered bad practise? or is that how it is usually done?

Thanks


Solution

  • The recommended way is to redraw your view's entire canvas. The doc for the deprecated method invalidate(Rect dirty) mentions

    The switch to hardware accelerated rendering in API 14 reduced
    the importance of the dirty rectangle. In API 21 the given rectangle is
    ignored entirely in favor of an internally-calculated area instead.
    

    Since hardware acceleration is enabled by default (even at view level) for API >=14, you can simply invalidate the entire view.

    Because of Hardware Acceleration there is very little performance impact. Hardware Acceleration utilizes Display Lists which further improves performance.

    In fact instead of worrying about using invalidate(), you can actually take care not to perform other things that can impact performance while drawing, refer: https://developer.android.com/guide/topics/graphics/hardware-accel#tips