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

文字颜色渐变效果(那串号码):

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

实现代码:

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

PS:网上很多帖子是重写onLayout()方法,能够实现颜色渐变,效果如下:
Android Textview实现文字颜色渐变效果_第2张图片

重写onLayout()方法的实现代码:

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

抱歉,博客做了下迁移,本文继续阅读请访问:Android Textview实现文字颜色渐变效果

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

你可能感兴趣的:(Android)