【问题标题】:How to set gradient as text color as well as add stroke around it in TextView Android?如何在 TextView Android 中将渐变设置为文本颜色以及在其周围添加描边?
【发布时间】:2022-01-03 11:43:45
【问题描述】:

我想将渐变设置为文本颜色,同时我希望文本在TextView 中也有一个实心笔触。到目前为止,我已经实现的是文本只能显示渐变或笔触,不能同时显示。

我创建了一个带有扩展 TextView 的自定义类,我正在使用以下方法:

用它来画笔画:

paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(_strokeWidth);
setTextColor(_strokeColor);

这给了我这个结果:

使用以下代码添加渐变:

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

它给了我以下结果:

问题是当我结合上述两种方法时,描边被绘制但描边的颜色与我给绘制对象的渐变相同。

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

【问题讨论】:

    标签: java android textview gradient


    【解决方案1】:

    所以在等待了4天多的时间和大量的研究之后,我终于能够成功实现预期的输出。

    我犯的错误是在绘画对象上绘制描边时,我将描边颜色设置为textcolor。这次我所做的是创建了一个LinearGradient() 对象并将其提供给paint.shader,同时设置paintStyle(Paint.Style.Stroke)

    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 一个笔触以及与textColor 一样的渐变。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-15
      • 1970-01-01
      • 2012-09-13
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-31
      相关资源
      最近更新 更多