Android textView文字渐变色设置

Android textView文字渐变色设置

方式一:

private void setGradientColor() {
        int[] colors = {Color.parseColor("#6C391C"), Color.parseColor("#A56B3C")};
        float[] position = {0f, 1.0f};
        LinearGradient mLinearGradient = new LinearGradient(0, 0, vplusCardTitle.getPaint().getTextSize() * vplusCardTitle.getText().length(), 0, colors, position, Shader.TileMode.CLAMP);
        vplusCardTitle.getPaint().setShader(mLinearGradient);
        vplusCardTitle.invalidate();

        LinearGradient mLinearGradient2 = new LinearGradient(0, 0, vplusCardMoney.getPaint().getTextSize() * vplusCardMoney.getText().length(), 0, colors, position, Shader.TileMode.CLAMP);
        vplusCardMoney.getPaint().setShader(mLinearGradient2);
        vplusCardMoney.invalidate();
    }

方式二:

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;


public class GradientColorTextView extends TextView {

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

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

    public void setGradientColor(int fromColor, int toColor) {
        this.fromColor = fromColor;
        this.toColor = toColor;
    }

    @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[]{fromColor, toColor},
                null, Shader.TileMode.REPEAT);
        mPaint.setShader(mLinearGradient);
        canvas.drawText(mTipText, getMeasuredWidth() / 2 - mTextBound.width() / 2, getMeasuredHeight() / 2 + mTextBound.height() / 2, mPaint);
    }
}

参考:

Android Textview实现文字颜色渐变效果_牛角尖呀的博客-CSDN博客_android文字渐变效果

Android Textview实现文字颜色渐变效果 - 编程猎人

Android TextView文字颜色渐变_ezconn的博客-程序员资料_android textview渐变 - 程序员资料

猜你喜欢

转载自blog.csdn.net/cpcpcp123/article/details/125653301