Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set gradient as the text color of a TextView? [duplicate]

I have a file containing a gradient( textgradient.xml) in my drawable folder. I need to put this gradient as the text color of a TextView through Java. How to do that?

like image 825
vergil corleone Avatar asked Jun 06 '13 09:06

vergil corleone


People also ask

How do you set the gradient color on Kotlin?

To create a gradient color we need to create a . xml file in the drawable folder. So go to app -> res -> drawable and right-click on drawable -> New -> Drawable Resource File and create gradient_drawable.


2 Answers

This links solves your query:

Text with gradient in Android

It used LinearGradient class to create a shader ,which is set on the text view

like image 65
Rachita Nanda Avatar answered Sep 23 '22 03:09

Rachita Nanda


It doesn't appear possible to extend TextView to draw text with a gradient. It is, however, possible to achieve this effect by creating a canvas and drawing on it. First we need to declare our custom UI element. In the initiation we need to create a subclass of Layout. In this case, we will use BoringLayout which only supports text with a single line.

Shader textShader=new LinearGradient(0, 0, 0, 20,
new int[]{bottom,top},
new float[]{0, 1}, TileMode.CLAMP);//Assumes bottom and top are colors defined above
textPaint.setTextSize(textSize);
textPaint.setShader(textShader);
BoringLayout.Metrics boringMetrics=BoringLayout.isBoring(text, textPaint);
boringLayout=new BoringLayout(text, textPaint, 0, Layout.Alignment.ALIGN_CENTER,
        0.0f, 0.0f, boringMetrics, false);

We then override onMeasure and onDraw:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
    setMeasuredDimension((int) textPaint.measureText(text), (int)      textPaint.getFontSpacing());
}

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

Our implementation of onDraw is at this point quite lazy (it completely ignores the measurement specs!, but so long as you guarantee that the view is given sufficent space, it should work okay.

Alternatively, it would be possible to inherit from a Canvas and override the onPaint method. If this is done, then unfortunately the anchor for text being drawn will always be on the bottom so we have to add -textPaint.getFontMetricsInt().ascent() to our y coordinate.

like image 22
blganesh101 Avatar answered Sep 21 '22 03:09

blganesh101