package com.android.app_base.widget;
|
|
import android.content.Context;
|
import android.content.res.TypedArray;
|
import android.graphics.Canvas;
|
import android.graphics.LinearGradient;
|
import android.graphics.Paint;
|
import android.graphics.Shader;
|
import android.util.AttributeSet;
|
|
import androidx.annotation.NonNull;
|
import androidx.annotation.Nullable;
|
import androidx.appcompat.widget.AppCompatTextView;
|
|
import com.android.app_base.R;
|
|
|
/**
|
* 自定义TextView
|
* 中间半透明和带渐变边框
|
*/
|
public class CustomTextView extends AppCompatTextView {
|
|
private float borderWidth;//边框宽度
|
private int borderColor;//边框颜色
|
private boolean isBorderGradient;//边框是否渐变
|
private int borderStartColor;//边框渐变开始颜色
|
private int borderEndColor;//边框渐变结束颜色
|
private float border_radius;//边框圆角
|
|
private Paint mPaint;
|
private LinearGradient shader;
|
|
public CustomTextView(@NonNull Context context) {
|
this(context,null);
|
}
|
|
public CustomTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
|
this(context, attrs,0);
|
}
|
|
public CustomTextView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
|
super(context, attrs, defStyleAttr);
|
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView);
|
borderWidth = a.getDimension(R.styleable.CustomTextView_border_width,0);
|
borderColor = a.getColor(R.styleable.CustomTextView_border_color,0);
|
isBorderGradient = a.getBoolean(R.styleable.CustomTextView_is_border_gradient,false);
|
borderStartColor = a.getColor(R.styleable.CustomTextView_border_gradient_start_color,borderColor);
|
borderEndColor = a.getColor(R.styleable.CustomTextView_border_gradient_end_color,borderColor);
|
border_radius = a.getDimension(R.styleable.CustomTextView_border_radius,0);
|
a.recycle();
|
|
//抗锯齿画笔
|
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
//防止边缘锯齿
|
mPaint.setAntiAlias(true);
|
mPaint.setStrokeJoin(Paint.Join.ROUND);
|
//需要重写onDraw就得调用此
|
this.setWillNotDraw(false);
|
|
}
|
|
@Override
|
protected void onDraw(Canvas canvas) {
|
|
super.onDraw(canvas);
|
//画边框
|
drawBorder(canvas);
|
|
}
|
private void drawBorder(Canvas canvas) {
|
mPaint.setStyle(Paint.Style.STROKE);
|
mPaint.setStrokeWidth(borderWidth);
|
if (isBorderGradient){
|
shader = new LinearGradient(0,0,getWidth(),0,borderStartColor,borderEndColor, Shader.TileMode.CLAMP);
|
mPaint.setShader(shader);
|
}else {
|
mPaint.setColor(borderColor);
|
}
|
if (border_radius > 0){
|
float realBorderWight = borderWidth / 2;
|
//需要把矩形大小左右上下各减去一半,不然圆角显示会有问题
|
canvas.drawRoundRect(realBorderWight,realBorderWight,getWidth()-realBorderWight,getHeight()-realBorderWight,border_radius,border_radius,mPaint);
|
}else{
|
canvas.drawRect(0,0,getWidth(),getHeight(),mPaint);
|
}
|
mPaint.setShader(null);
|
}
|
}
|