Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Android support non-linear progression in gradients?

I would like a gradient that progresses from a start color to an end color at a non-linear rate. The gradient would change only along a single cartesian axis. A RadialGradient or SweepGradient is not what I am referring to here.

My question is, does Android provide support for controlling gradient transition rates, without writing a custom Shader?

like image 729
MM. Avatar asked Apr 27 '15 23:04

MM.


2 Answers

Not a good way, but an easy way:

You can add a centerColor in your gradient XML file and set a value you want. That makes it non-linear (You need to do some calculations).

For example, if you need a non-linear gradient from Transparent to Black, you can do it like this:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#00000000"
        android:centerColor="#11000000"
        android:endColor="#000000"
        android:angle="270" />
</shape>
like image 133
Ehsan Heidari Avatar answered Nov 11 '22 17:11

Ehsan Heidari


Yes, to a certain degree. LinearGradient has a constructor that takes multiple colors and positions, so you can approximate non-linear progression using piece-wise linear function.

The code below is based on answer https://stackoverflow.com/a/4381192/8568479

ShapeDrawable.ShaderFactory shaderFactory = new ShapeDrawable.ShaderFactory() {
    @Override
    public Shader resize(int width, int height) {
        LinearGradient gradient = new LinearGradient(0, 0, width, height,
            new int[] { 
                Color.parseColor("#000000"),
                Color.parseColor("#777777"),
                Color.parseColor("#FFFFFF")
            },
            new float[] { 0, 0.3f, 1 },
            Shader.TileMode.REPEAT
        );
        return gradient;
    }
};

PaintDrawable p = new PaintDrawable();
p.setShape(new RectShape());
p.setShaderFactory(shaderFactory);

You can add as many stops as you need to make the gradient look smooth. I've also found this link helpful to select the coefficients for a smooth-looking gradient https://css-tricks.com/easing-linear-gradients/

like image 1
fdermishin Avatar answered Nov 11 '22 17:11

fdermishin