参考帖子:
https://www.cnblogs.com/itchq/p/4138966.html
https://blog.csdn.net/inwhites/article/details/81917086
https://www.jianshu.com/p/a9d09cb7577f
LinearGradientFontSpan.java:
/**
* FileName: LinearGradientFontSpan
* Author: bai
* Date: 2019/4/17 15:26
*/
public class LinearGradientFontSpan extends ReplacementSpan {
private int mSize;
private int mode;
public LinearGradientFontSpan(int mode) {
this.mode = mode;
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
mSize = Math.round(paint.measureText(text, start, end));
//这段不可以去掉,字体高度没设置,可能出现draw()方法没有被调用,如果你调用SpannableStringBuilder后append一个字符串,效果也是会出来,下面这段就不需要了
// 原因详见https://stackoverflow.com/questions/20069537/replacementspans-draw-method-isnt-called
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(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
float rrr = paint.descent() - paint.ascent();
LinearGradient lg = null;
if(mode == 0){//上下渐变
lg = new LinearGradient(0, 0, 0, paint.descent() - paint.ascent(),
0xffff0000,
0xff00ff00,
Shader.TileMode.REPEAT); //从上到下渐变
}else{//左右渐变
// lg = new LinearGradient(0, 0, mSize, 0,
// new int[] { 0xffff0000, 0xffffffff, 0xff00ff00 },
// new float[] { 0,0.5f, 0.8f},
// Shader.TileMode.REPEAT); //从左到右渐变
//lg = new LinearGradient(paint.descent() - paint.ascent(),0,0,0,new int[]{Color.RED,Color.BLACK,Color.YELLOW},new float[]{0,0.5f,1}, Shader.TileMode.REPEAT);
lg = new LinearGradient(mSize,0,0,0,new int[]{Color.RED,Color.BLACK,Color.YELLOW},new float[]{0,0.5f,1}, Shader.TileMode.REPEAT);
}
paint.setShader(lg);
canvas.drawText(text, start, end, x, y, paint);//绘制文字
}
}
MainActivity.java使用:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val spannable = SpannableString("城市的夜晚霓虹灯璀璨\n" +",点亮了黑暗赶不走孤单")
val span = LinearGradientFontSpan( 1)
spannable.setSpan(span,3,8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
spannableTextView.text=spannable
//文字上下渐变
val result = getRadiusGradientSpan("城市的夜晚霓虹灯璀璨\n,点亮了黑暗赶不走孤单")
spannableVerticalTextView.text=result
}
private fun getRadiusGradientSpan(string:String):SpannableString{
val spannableStringBuilder = SpannableString(string);
val span = LinearGradientFontSpan(0);
spannableStringBuilder.setSpan(span, 0, spannableStringBuilder.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableStringBuilder;
}
}
demo源码:https://download.csdn.net/download/u010326875/11125338