josemigallas
josemigallas

Reputation: 3918

Linear Gradient CenterX

I am trying to make a transparent gradient background for a button, something like this:

(The start color is not grey but transparent)

Desired gradient

But I am getting this: (where white portion is too narrow)

enter image description here

This is my gradient.xml:

<!-- Here centerX does not work -->
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <gradient
        android:centerX="30%"
        android:startColor="@android:color/transparent"
        android:endColor="@android:color/white"/>

</shape>

I have also tried adding a centerColor, but then the transparent area turns to grey!

<!-- Here the startColor turns greyish -->
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <gradient
        android:centerColor="@android:color/white"
        android:centerX="30%"
        android:endColor="@android:color/white"
        android:startColor="@android:color/transparent" />

</shape>

Thanks in advance!

Upvotes: 2

Views: 6302

Answers (2)

Vedant Agarwala
Vedant Agarwala

Reputation: 18819

centerX works only when you have a centerColor set.

But if you set the center color to @android:color/transparent the gradient goes from opaque white to transparent black, not white.

@android:color/transparent is defined as #00000000, which is a transparent black and not white. Usually it doesn't matter because color is transparent anyway, but in case of gradients it gives a black tint.

So, you need

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <gradient
        android:startColor="#00ffffff"
        android:centerColor="#00ffffff"
        android:endColor="#ffffffff"
        android:centerX="30%" />
</shape>

In this case the color is same (#ffffff i.e. white) across the gradient, but alpha is varied from 00 to ff.

Upvotes: 2

R. Zag&#243;rski
R. Zag&#243;rski

Reputation: 20278

If what you need is just gradient moved to the left side of the drawable, try something like this:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:left="100dp">
        <color android:color="@android:color/white"/>
    </item>
    <item android:width="100dp">
        <shape
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="rectangle">
        <gradient
            android:centerX="30%"
            android:endColor="@android:color/white"
            android:startColor="@android:color/transparent"/>
        </shape>
    </item>
</layer-list>

This layer consist of two rectangles:

  1. White rectangle moved to the right by 30dp
  2. Gradient rectangle, whose width is 30dp

Upvotes: 2

Related Questions