一、先来看下效果图
二、实现思路与原理
1、字体渐变色,只需要给TextView的Paint添加渐变色shader即可
@Override
protected void onDraw(Canvas canvas) {
LinearGradient linearGradient = new LinearGradient(0, 0, getWidth(), 0, gradientColors, gradientPositions, Shader.TileMode.CLAMP);
getPaint().setShader(linearGradient);
super.onDraw(canvas);
}
2、字体加粗边在绘制TextView之前,先给TextView的画笔设置画笔宽度,然后先绘制粗边再把画笔宽度设置回去,然后再绘制原本的内容
@Override
protected void onDraw(Canvas canvas) {
TextPaint textPaint = getPaint();
Paint.Style oldStyle = textPaint.getStyle();
//首先设置画笔宽度就出现粗边
textPaint.setStrokeWidth(strokeWidth);
textPaint.setStyle(Paint.Style.FILL_AND_STROKE);
//如需渐变色加上shader
LinearGradient linearGradient = new LinearGradient(0, 0, getWidth(), 0, gradientColors, gradientPositions, Shader.TileMode.CLAMP);
textPaint.setShader(linearGradient);
//然后调用 super.onDraw(canvas) 就绘制出来了
super.onDraw(canvas);
//绘制完粗边接着把画笔宽度设置回去
textPaint.setStrokeWidth(0);
textPaint.setStyle(oldStyle);
//如需渐变色加上shader
LinearGradient linearGradient = new LinearGradient(0, 0, getWidth(), 0, gradientColors, gradientPositions, Shader.TileMode.CLAMP);
textPaint.setShader(linearGradient);
//然后再绘制原本内容
super.onDraw(canvas);
}
三、我已经将项目开源,可以直接使用,Github开源地址:
https://github.com/FlyJingFish/GradientTextView
使用起来非常简单,例如:
<com.flyjingfish.gradienttextviewlib.GradientTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text=" Hello World! "
android:textColor="@color/white"
android:textSize="30sp"
app:gradient_angle="0"
app:gradient_endColor="@color/white"
app:gradient_startColor="@color/teal_200"
app:gradient_stroke_angle="0"
app:gradient_stroke_strokeWidth="6dp"
app:gradient_stroke_textColor="@color/purple_700" />
版权声明:本文为u013077428原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。