Search code examples
androidtextviewtransparencygradient

LinearGradient and transparent colors in TextView


I used Linear Gradient to set gradient color in TextView and found very interesting situation. To set TextView gradient I used this code:

int c1 = getResources().getColor(R.color.test1);
int c2 = getResources().getColor(R.color.test2);
Shader shader = new LinearGradient(0, 0, 0, status.getTextSize(),
                                   new int[]{c1, c2},
                                   new float[]{0, 1}, Shader.TileMode.CLAMP);
status.getPaint().setShader(shader);

I played a little bit with color

  1. Set only c1=green and c2-transparent
    <color name="test1">#ff00ff00</color>
    <color name="test2">#000000ff</color>
    

enter image description here

  1. Set only c2=blue and c1-transparent
    <color name="test1">#0000ff00</color>
    <color name="test2">#ff0000ff</color>
    

enter image description here

So I don't see transparent in second case.

Can somebody explain the nature of this gradient builder?

Update: Thanks to @Romain Guy for his answer. I play more with gradient and got almost what I want:

    Shader shader = new LinearGradient(0, 0, 0, status.getTextSize(),
            new int[]{c1, c2, colour, colour},
            new float[]{0.2f, 0.7f, 0.699f, 1}, Shader.TileMode.CLAMP);

and status.setIncludeFontPadding();

true: enter image description here

false: enter image description here

And as you can see center border of solid color and gradient color shifting according to padding value.

Can we calculate float values of gradients borders to get exactly the center of characters in TextView? I think it will depend on FontType.


Solution

  • The translucency effect is there. The problem is that you start the gradient at 0, which is above the text. You should probably take into account the padding of the TextView and/or the FontMetrics of the font you're using.