背景
在日常开发中经常会遇到各种渐变的TextView,为了加快开发进度就记录下方便以后直接使用。
效果图
实现
public class ColorsTextViewextends TextView {
private LinearGradientmLinearGradient;
private PaintmPaint;
//TextView宽度
private int mViewWidth =0;
//TextView高度
private int mViewHeight =0;
private RectmTextBound =new Rect();
//存放颜色
private int[]mColorList;
//渲染方向 默认:横向
private boolean isVertrial;
public ColorsTextView(Context context) {
super(context);
}
public ColorsTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mColorList =new int[]{0xFFffffff, 0xFF000000, 0xFF000000, 0xFFffffff};
}
@Override
protected void onDraw(Canvas canvas) {
if (isVertrial) {
mViewHeight = getMeasuredHeight();
}else {
mViewWidth = getMeasuredWidth();
}
mPaint = getPaint();
String mTipText = getText().toString();
mPaint.getTextBounds(mTipText, 0, mTipText.length(), mTextBound);
mLinearGradient =new LinearGradient(0, 0, mViewWidth, mViewHeight, mColorList, null, Shader.TileMode.CLAMP);
mPaint.setShader(mLinearGradient);
canvas.drawText(mTipText, getMeasuredWidth() /2 -mTextBound.width() /2, getMeasuredHeight() /2 +mTextBound.height() /2, mPaint);
}
public void setVertrial(boolean vertrial) {
isVertrial = vertrial;
}
public void setmColorList(int[] mColorList) {
if (mColorList !=null && mColorList.length <2) {
throw new RuntimeException("mClorList's length must be > 2");
}else {
this.mColorList = mColorList;
}
}
}
使用
<com.example.textviewmovedemo.view.ColorsTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OPPO"
android:textSize="30dp"/>
好了,到此结束了。希望用的小伙伴帮忙点下赞,谢谢~