- 编写
LinearGradientFontSpan
继承ReplacementSpan
public class LinearGradientFontSpan extends ReplacementSpan {
private int mSize;
private int startColor;
private int endColor;
public LinearGradientFontSpan(int startColor, int endColor) {
this.startColor = startColor;
this.endColor = endColor;
}
@Override
public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, @Nullable Paint.FontMetricsInt fm) {
mSize = (int) paint.measureText(text , start , end);
Paint.FontMetricsInt metrics = paint.getFontMetricsInt();
if (fm != null) {
fm.top = metrics.top;
fm.ascent = metrics.ascent;
fm.descent = metrics.descent;
fm.bottom = metrics.bottom;
}
return mSize;
}
@Override
public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) {
LinearGradient lg = new LinearGradient(0, 0, 0, paint.descent() - paint.ascent(),
startColor,
endColor,
Shader.TileMode.REPEAT); //从上到下渐变
paint.setShader(lg);
canvas.drawText(text, start, end, x, y, paint);//绘制文字
}
}
- 使用
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.text_view);
//这里使用刚创建的工具类
LinearGradientFontSpan linearGradientFontSpan = new LinearGradientFontSpan(Color.RED, Color.BLUE);
SpannableString spannableString = new SpannableString("hello");
//第一个参数是格式,第二个参数起始位置,第三个结束位置(但不包括结束位置),,第四个模式,共有四种
spannableString.setSpan(linearGradientFontSpan , 2 , 5 , Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);//设置spann
}
}
原文链接:https://blog.csdn.net/csdn_zxw/article/details/108306276
网友评论