如何在Android TextView中将渐变设置为文本颜色并添加描边?

8
我希望将渐变设置为文本颜色,并同时在TextView中使文本具有固体描边效果。到目前为止,我只能实现文本显示渐变或者描边,无法同时实现两者。
我创建了一个扩展TextView的自定义类,并使用以下方法:
使用此方法绘制描边:
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(_strokeWidth);
setTextColor(_strokeColor);

这让我得到了如下结果:

enter image description here

使用以下代码添加渐变效果:

Shader textShader = new LinearGradient(0f, 0f, getWidth(), getTextSize(), gradientColorsArray, null, Shader.TileMode.CLAMP);
                paint.setShader(textShader);

以下是我的结果:

enter image description here

问题在于当我结合上述两种方法时,笔画被绘制了,但笔画的颜色与我给绘图对象的渐变颜色相同。

以下是我想要实现的结果。如果有人能指导我如何实现期望的效果,那就太好了。

enter image description here

1个回答

3

经过等待四天和大量的研究,我终于成功实现了所需的输出。

我之前犯的错误是在画一个paint object时,将描边颜色设置为textcolor,而这一次我创建了一个LinearGradient()对象,并在设置paintStyle(Paint.Style.Stroke)时将其赋给了paint.shader

Paint paint = this.getPaint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(5f);
        paint.setShader(new LinearGradient(0f, 0f, getTextSize(), getTextSize(), mOutlineColor, mOutlineColor, Shader.TileMode.CLAMP));

在我的CustomTextView类的onDraw()方法中设置描边后,我调用了super.onDraw(canvas)

然后我创建了一个新的LinearGradient()对象来实现渐变色:

 Paint paint = this.getPaint();
        paint.setStyle(Paint.Style.FILL);
        Shader linearShader = new LinearGradient(0f, 0f, getWidth(), getTextSize(), colors, null,
                Shader.TileMode.CLAMP);
        paint.setShader(linearShader);

最后再次调用super.onDraw(canvas),这将使我的textview具有描边和渐变作为文本颜色。

非常感谢!我从开始项目的第一天就一直在寻找它,现在可以删除我的文本图像,使用正确的图像了! - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接