Android 中带有渐变的文本 [英] Text with gradient in Android
问题描述
如何扩展 TextView
以允许绘制具有渐变效果的文本?
似乎无法扩展 TextView 以绘制带有渐变的文本.但是,可以通过创建画布并在其上绘图来实现此效果.首先,我们需要声明我们的自定义 UI 元素.在初始化中,我们需要创建 布局.在这种情况下,我们将使用 BoringLayout,它只支持带有单个文本的文本线.
Shader textShader=new LinearGradient(0, 0, 0, 20,新的 int[]{bottom,top},new float[]{0, 1}, TileMode.CLAMP);//假设底部和顶部是上面定义的颜色textPaint.setTextSize(textSize);textPaint.setShader(textShader);BoringLayout.MetricsboringMetrics=BoringLayout.isBoring(text, textPaint);BoringLayout=new BoringLayout(text, textPaint, 0, Layout.Alignment.ALIGN_CENTER,0.0f,0.0f,boringMetrics,假);
然后我们覆盖onMeasure
和onDraw
:
@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){setMeasuredDimension((int) textPaint.measureText(text), (int) textPaint.getFontSpacing());}@覆盖受保护的无效 onDraw(画布画布){super.onDraw(画布);无聊的布局.绘制(画布);}
我们对 onDraw
的实现在这一点上非常懒惰(它完全忽略了测量规范!但只要你保证给视图足够的空间,它应该可以正常工作.>
或者,可以从 Canvas
继承并覆盖 onPaint
方法.如果这样做,那么不幸的是,绘制文本的锚点将始终位于底部,因此我们必须将 -textPaint.getFontMetricsInt().ascent()
添加到我们的 y 坐标.
How would I extend TextView
to allow the drawing of text with a gradient effect?
It doesn't appear possible to extend TextView to draw text with a gradient. It is, however, possible to achieve this effect by creating a canvas and drawing on it. First we need to declare our custom UI element. In the initiation we need to create a subclass of Layout. In this case, we will use BoringLayout which only supports text with a single line.
Shader textShader=new LinearGradient(0, 0, 0, 20,
new int[]{bottom,top},
new float[]{0, 1}, TileMode.CLAMP);//Assumes bottom and top are colors defined above
textPaint.setTextSize(textSize);
textPaint.setShader(textShader);
BoringLayout.Metrics boringMetrics=BoringLayout.isBoring(text, textPaint);
boringLayout=new BoringLayout(text, textPaint, 0, Layout.Alignment.ALIGN_CENTER,
0.0f, 0.0f, boringMetrics, false);
We then override onMeasure
and onDraw
:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
setMeasuredDimension((int) textPaint.measureText(text), (int) textPaint.getFontSpacing());
}
@Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
boringLayout.draw(canvas);
}
Our implementation of onDraw
is at this point quite lazy (it completely ignores the measurement specs!, but so long as you guarantee that the view is given sufficent space, it should work okay.
Alternatively, it would be possible to inherit from a Canvas
and override the onPaint
method. If this is done, then unfortunately the anchor for text being drawn will always be on the bottom so we have to add -textPaint.getFontMetricsInt().ascent()
to our y coordinate.
这篇关于Android 中带有渐变的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!