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

文字颜色渐变效果图

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

实现方案

方案一:继承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));

        }

    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值