Search code examples
androidcanvasgradientondraw

Android - Lightweight Gradients


From Android's Developer Reference:

LinearGradient(float x0, float y0, float x1, float y1, int[] colors, float[] positions, Shader.TileMode tile)

So I'm wondering if there's a way to draw a gradient in the onDraw() method? The problem here being that I need to enter the coordinates for whatever I'm about draw the gradient on. What if I need the same gradient on multiple shapes of different sizes and positions? Even more important, what if the shape I'm drawing the gradient on, changes it's position? Even Android Studio advises you to not do initialization of variables inside the onDraw() method.

Thanks!


Solution

  • What I was able to do, is create a drawable with a gradient in an .xml file.

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item>
            <shape>
                <gradient
                    android:startColor="@android:color/holo_blue_light"
                    android:endColor="@android:color/holo_red_dark"
                    android:angle="45"/>
            </shape>
        </item>
    </selector>
    

    Then in your onDraw() do (obviously inside an init function, because you will only need to initialize once, at least I did):

    Drawable d = ContextCompat.getDrawable(context, R.drawable.indicator_active);
    

    And to draw it, just do

    d.setBounds(l, t, r, b);
    d.draw(canvas);
    

    If anyone knows of an easier/more flexible way, let me know!