Android实现EditText文本颜色渐变
先上效果图
刚开始想着先是设置textColor属性就可以了,然后写了个一个带渐变的shap感觉不好使,于是乎就自定义解决,代码如下
代码语言:javascript复制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.EditText;
public class MyEditText extends EditText {
public MyEditText(Context context) {
this(context, null);
}
public MyEditText(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
private Paint mPaint;
private int mViewHeight = 0;
private Rect mTextBound = new Rect();
private LinearGradient mLinearGradient;
@Override
protected void onDraw(Canvas canvas) {
mViewHeight = getMeasuredHeight();
mPaint = getPaint();
String mText = getText().toString();
mPaint.getTextBounds(mText, 0, mText.length(), mTextBound);
mLinearGradient = new LinearGradient(0, 0, 0, mViewHeight,
new int[]{0xFF8EDA4D, 0xFF4EB855}, null, Shader.TileMode.REPEAT);
mPaint.setShader(mLinearGradient);
canvas.drawText(mText, getMeasuredWidth() / 2 - mTextBound.width() / 2, getMeasuredHeight() / 2 mTextBound.height() / 2, mPaint);
}
}
我这里实现的是上下的渐变色,当然每个人的需求都不一样,有的要实现左右渐变色,只要在这句中设置其属性即可mLinearGradient = new LinearGradient(0, 0, 0, mViewHeight, new int[]{0xFF8EDA4D, 0xFF4EB855}, null, Shader.TileMode.REPEAT)
本文首发于我的微信公众号,更多干货文章,请扫描二维码订阅哦: