1

I have an oval shape with a sweep gradient, I want to rotate the gradient not the oval itself (since when I rotate oval it is not in the right position anymore). I couldn't find anything about this. Any ideas? This is what I'm trying to do

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>

        <shape xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="oval">
            <stroke
                android:width="1dp"
                android:color="#585858" />
            <rotate
                android:fromDegrees="0"
                android:pivotX="50%"
                android:pivotY="50%"
                android:toDegrees="40">
                <gradient
                    android:endColor="#FF7DD6"
                    android:startColor="#FFFFFF"
                    android:type="sweep"
                    android:useLevel="false" />
            </rotate>

        </shape>

    </item>

</layer-list>
cagdas
  • 150
  • 1
  • 1
  • 14

2 Answers2

3

If you are using SweepGradient there is setLocalMatrix method that could be used:

 float initial_rotation_angle_degrees = 30; 
 SweepGradient gradient = new SweepGradient(0,0
                        ,new int[]{
                        ,0xff0078be
                        ,0xfff4535c
                        }
                        ,null);
        Matrix matrix = new Matrix();
// Rotating the gradient 
        matrix.postRotate(initial_rotation_angle_degrees);
// Translating the gradient (The initial cx, cy values must be 0)
        matrix.postTranslate(cx,cy);
        gradient.setLocalMatrix(matrix);
Kvant
  • 1,407
  • 17
  • 18
  • The method `postRotate(float degrees, float px, float py)` also helpful. it will rotate base on `px `and `py` – Linh May 09 '21 at 15:04
1

gradient has an attribute angle that takes an int value to give direction to a gradient.

According to the docs:

The angle for the gradient, in degrees. 0 is left to right, 90 is bottom to top. It must be a multiple of 45. Default is 0.

By changing the angle, this should rotate your gradient.

An example might be:

<gradient
     android:endColor="#FF7DD6"
     android:startColor="#FFFFFF"
     android:type="sweep"
     android:angle="270"
     android:useLevel="false" />
Ed George
  • 4,928
  • 2
  • 33
  • 57
  • Thanks for the reply. Unfortunately, That doesn't work for sweep gradient but it works for linear gradient [link](http://stackoverflow.com/questions/12153890/angle-attribute-in-android-gradient) – cagdas Jul 14 '16 at 21:10
  • Apologies @cagdas, I didn't initially notice it was a sweep. – Ed George Jul 15 '16 at 08:48