Android Textview实现文字颜色渐变效果

文字颜色渐变效果图

下图中那串数字就处于重写的TextView中:

Android Textview实现文字颜色渐变效果_第1张图片

实现方案

方案一:继承TextView,重写onDraw()方法

import android.widget.TextView;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import android.util.AttributeSet;

/**
 * Created by ZuoHailong on 2017/11/14.
 */

public class GradientColorTextView extends TextView {

    private LinearGradient mLinearGradient;
    private Paint mPaint;
    private int mViewWidth = 0;
    private Rect mTextBound = new Rect();

    public GradientColorTextView (Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mViewWidth = getMeasuredWidth();
        mPaint = getPaint();
        String mTipText = getText().toString();
        mPaint.getTextBounds(mTipText, 0, mTipText.length(), mTextBound);
        mLinearGradient = new LinearGradient(0, 0, mViewWidth, 0,
                new int[]{0xFFFFEABA, 0xFFBE8B49},
                null, Shader.TileMode.REPEAT);
        mPaint.setShader(mLinearGradient);
        canvas.drawText(mTipText, getMeasuredWidth() / 2 - mTextBound.width() / 2, getMeasuredHeight() / 2 + mTextBound.height() / 2, mPaint);
    }
}

方案二:继承TextView,重写onLayout()方法。

要注意的是,TextView不可以设置TextColor属性了,否则与onLayout()中设置的渐变颜色叠加渲染,会出现色差。

import android.widget.TextView;
import android.content.Context;
import android.graphics.LinearGradient;
import android.graphics.Shader;
import android.util.AttributeSet;

/**
 * Created by ZuoHailong on 2017/11/14.
 */

public class GradientColorTextViewForManagerName extends TextView {
    public GradientColorTextViewForManagerName(Context context) {
        super(context);
    }

    public GradientColorTextViewForManagerName(Context context,
                                               AttributeSet attrs) {
        super(context, attrs);
    }
    public GradientColorTextViewForManagerName(Context context,
                                               AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onLayout(boolean changed,
                            int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (changed) {
            getPaint().setShader(new LinearGradient(
                    0, 0, getWidth(), getHeight(),
                    new int[]{0xFFFFEABA, 0xFFDFBB82, 0xFFBE8B49}, new float[]{0, 0.5f, 1},
                    Shader.TileMode.CLAMP));
        }
    }
}

 

你可能感兴趣的:(Android,UI)