在Android的梯度文本 [英] Text with gradient in Android

查看:90
本文介绍了在Android的梯度文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么会延长的TextView 来使文字的绘制带有渐变效果?

How would I extend TextView to allow the drawing of text with a gradient effect?

推荐答案

它不会出现可能延长的TextView与渐变绘制文本。然而,有可能通过创建画布和上绘制来达到这种效果。首先,我们需要<一个href="http://stackoverflow.com/questions/2695646/declaring-a-custom-android-ui-element-using-xml">declare我们自定义的UI元素。在开始,我们需要创建的子类<一href="http://developer.android.com/reference/android/text/Layout.html#draw%28android.graphics.Canvas%29">Layout.在这种情况下,我们会使用 BoringLayout 只支持文本一行。

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);

我们再重写 onMeasure 的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);
}

我们的实施的OnDraw 的是在这一点上很懒惰(它完全忽略了测量规范!但只要你保证视图给出sufficent空间,它应该没问题。

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.

另外,也有可能从画布继承和覆盖的OnPaint 方法。如果做到这一点,正在绘制然后不幸的锚文本将始终在底部,所以我们必须添加 -textPaint.getFontMetricsInt()。上升()我们的ÿ坐标。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆