Skip to content

Instantly share code, notes, and snippets.

@mirmilad
Created February 4, 2020 22:21
Show Gist options
  • Save mirmilad/97182248c42d8477bb5edf07e5b40a08 to your computer and use it in GitHub Desktop.
Save mirmilad/97182248c42d8477bb5edf07e5b40a08 to your computer and use it in GitHub Desktop.
A simple method to set LinearGradient as text color to TextView
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import android.text.Layout;
import android.widget.TextView;
public class GradientTextViewUtil {
public static void setGradientTextColor(TextView textView, float angle, int[] colors) {
setGradientTextColor(textView, angle, colors, null);
}
public static void setGradientTextColor(final TextView textView, final float angle, final int[] colors, final float[] positions) {
textView.post(new Runnable() {
@Override
public void run() {
final Rect textBound = new Rect(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE);
final Layout layout = textView.getLayout();
for(int i = 0; i < textView.getLineCount(); i++) {
float left = layout.getLineLeft(i);
float right = layout.getLineRight(i);
if(left < textBound.left) textBound.left = (int)left;
if(right > textBound.right) textBound.right = (int)right;
}
textBound.top = layout.getLineTop(0);
textBound.bottom = layout.getLineBottom(textView.getLineCount() - 1);
if(textView.getIncludeFontPadding()) {
Paint.FontMetrics fontMetrics = textView.getPaint().getFontMetrics();
textBound.top += (fontMetrics.ascent - fontMetrics.top);
textBound.bottom -= (fontMetrics.bottom - fontMetrics.descent);
}
double angleInRadians = Math.toRadians(angle);
double r = Math.sqrt(Math.pow(textBound.bottom - textBound.top, 2) +
Math.pow(textBound.right - textBound.left, 2)) / 2;
float centerX = textBound.left + (textBound.right - textBound.left) / 2;
float centerY = textBound.top + (textBound.bottom - textBound.top) / 2;
float startX = (float)Math.max(textBound.left, Math.min(textBound.right, centerX - r * Math.cos(angleInRadians)));
float startY = (float)Math.min(textBound.bottom, Math.max(textBound.top, centerY - r * Math.sin(angleInRadians)));
float endX = (float)Math.max(textBound.left, Math.min(textBound.right, centerX + r * Math.cos(angleInRadians)));
float endY = (float)Math.min(textBound.bottom, Math.max(textBound.top, centerY + r * Math.sin(angleInRadians)));
Shader textShader = new LinearGradient(startX, startY, endX, endY, colors, positions,
Shader.TileMode.CLAMP);
textView.setTextColor(Color.WHITE);
textView.getPaint().setShader(textShader);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment