最近接到一个需求要求字体垂直渐变当然不带动画 只有字体颜色渐变 同时要设置字体风格
后面的就是实现需求了 然而当我实现起来。。起初实现了ondraw onlayout 等等等等 wtf' 绘制是如此费劲
后来细看Gradient 就是线性渐变。。其实不管怎么写也都得用这个 开始直接设置这些是没问题的,比如这样
设置起始颜色 gettextSize 就是字体大小了 这样在y轴表示纵向 你可以尝试改变其他三个位置来试试
LinearGradient mLinearGradient = new LinearGradient(0, 0, 0,
tv.getPaint().getTextSize(),
Color.white,Color.black,
Shader.TileMode.CLAMP);
tv.getPaint().setShader(mLinearGradient);
但是我显示出来的效果并不是很好颜色值对不上,,,,wtf 猜测是因为当textView包裹内容时我们设置了字体大小会自动有内边距开始渐变并不是从字上开始的是从整个控件开始的比如下面

wtf 效果不对 不是从我想要的颜色开始。。。
后来看到 有这样一种方法 颜色数组 位置数组。。简直快速开发蒙骗测试之良心方法啊
LinearGradient(float x0, float y0, float x1, float y1, @NonNull @ColorInt int colors[],
@Nullable float positions[], @NonNull TileMode tile)
于是我这样写了下
setTextColorGradient(mTv1, Color.WHITE,Color.parseColor("#5A5A5A"),0.6f,0.8f);
public void setTextColorGradient(TextView tv, int startColor, int endColor, float start, float end) {
LinearGradient mLinearGradient = new LinearGradient(0, 0, 0,
tv.getPaint().getTextSize(),
new int[]{startColor, endColor},
new float[]{start, end},
Shader.TileMode.CLAMP);
tv.getPaint().setShader(mLinearGradient);
}
效果就变成了这样。。。。
具体效果自己根据坐标调
奉上方法
/**
* 修改字体
* @param tv
*/
public void setTextFont(TextView tv) {
/*assets目录下新建 fonts 并将资源放到里面并按照如下方式读取设置*/
Typeface fontFace1 = Typeface.createFromAsset(getAssets(),
"fonts/DIN-MEDIUM.OTF");
Typeface fontFace2 = Typeface.createFromAsset(getAssets(),
"fonts/DINENGSCHRIFT.OTF");
tv.setTypeface(fontFace1);
}
/**
* @param tv 控件
* @param startColor 开始颜色 Color.WHITE
* @param endColor 结束颜色 Color.parseColor("#5A5A5A")
* @param start 开始位置 0.4f
* @param end 结束位置 0.9f
*/
public void setTextColorGradient(TextView tv, int startColor, int endColor, float start, float end) {
LinearGradient mLinearGradient = new LinearGradient(0, 0, 0,
tv.getPaint().getTextSize(),
new int[]{startColor, endColor},
new float[]{start, end},
Shader.TileMode.CLAMP);
tv.getPaint().setShader(mLinearGradient);
}
/**
* @param tv 控件
* @param colorList 开始到结束颜色集合 new int[] { sratrColor,endColor}
* @param locationList 对应上述颜色的坐标点 new float[]{0f,1.0f}
*/
public void setTextColorGradient(TextView tv, int[] colorList, float[] locationList) {
LinearGradient mLinearGradient = new LinearGradient(0, 0, 0,
tv.getPaint().getTextSize(),
colorList,
locationList,
Shader.TileMode.CLAMP);
tv.getPaint().setShader(mLinearGradient);
}
三周写一个应用第二周设计图才出来妈的 真是要命啊
本文详细介绍了如何在Android中使用TextView实现字体的垂直渐变效果,包括解决颜色值对不上的问题,以及如何通过调整坐标来获得理想的渐变效果。
4674

被折叠的 条评论
为什么被折叠?



