Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the center color be repositioned in an android radial-gradient drawable?

It is easy to achieve the below gradient at left using standard start, center, and end colors in a radial gradient with android in which the start = yellow, center = purple, and end = blue. The circle at right however requires the repositioning of the center color. Is this possible?

enter image description here

The result at left can be reproduced with something like:

    <shape android:shape="oval">
        <gradient
            android:endColor="#0000ff"
            android:gradientRadius="my_radius"
            android:centerColor="#770077"
            android:startColor="#00ffff"
            android:type="radial"/>
    </shape>

I am wondering if I can shift the center color to achieve the gradient at right. I believe the answer is no, but I would like to see if anyone has discovered a way in which to do this. Thanks!

like image 873
Daniel Smith Avatar asked Oct 25 '12 23:10

Daniel Smith


1 Answers

Sadly, this cannot be achieved via XML declarations, however, it is possible to do via code.

Here's a quick code sample:

public class MyDrawing extends View 
{   
    private Paint mPaint;

    public MyDrawing(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        init();
    }

    public MyDrawing(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init();
    }

    public MyDrawing(Context context)
    {
        super(context);
        init();
    }

    private void init()
    {
        int [] colors = new int[] { 0xff0000ff, 0xff00ff00, 0xffff0000 };
        float [] positions = new float[] { 0.4f, 0.7f, 0.9f };

        RadialGradient gradient = new RadialGradient(50, 50, 50, colors, positions, TileMode.CLAMP);                
        mPaint = new Paint();
        mPaint.setDither(true);
        mPaint.setShader(gradient);
    }

    @Override
    protected void onDraw(Canvas canvas) 
    {           
        super.onDraw(canvas);                               

        canvas.drawCircle(circleX, circleY, circleRadius, mPaint);      
    }
}

Two things you should pay attention to:

  1. In the colors array, you must specify the alpha (the 1st to chars). In my example, I specified both as "ff", meaning no transparency. If you don't specify the alpha, it will default to 0.

  2. The positions array specifies the positioning or strength of each color in the gradient. Play around with this to achieve the result you're looking for.

Hope this helps :)

like image 72
Gil Moshayof Avatar answered Nov 15 '22 19:11

Gil Moshayof