最近做应用的时候遇到一个需求,一行文字的颜色需要一个渐变效果
如上所有 从左到有逐渐变化,自己写了一个demo实现上述效果
package com.huwei.example.test;
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;
import android.widget.TextView; public class MyTextView extends TextView { private LinearGradient mLinearGradient;
private Paint mPaint;
private int mViewWidth = 0;
private Rect mTextBound = new Rect();
public MyTextView(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[] { 0xFF429321, 0xFFB4EC51 },
null, Shader.TileMode.REPEAT);
mPaint.setShader(mLinearGradient);
canvas.drawText(mTipText, getMeasuredWidth() / 2 - mTextBound.width() / 2, getMeasuredHeight() / 2 + mTextBound.height()/2, mPaint);
} }
核心实现是用了一个LinaerGradient 给paint设置一个LinaerGradient
利用这个LinaerGradient 也可以实现一些其他类似效果,如以下颜色渐变的线条,颜色渐变的图片等