- 对于实现该功能首先必须要对自定义控件有一定的知识了解
- 本实例只需要知道
1、onDraw(Canvas canvas)
2、onMeasure(int widthMeasureSpec, int heightMeasureSpec)
其实这两个放的作用很明确的,使用Measure重新测量view的空间,使用onDraw绘制需要的样子。
这里主要实现绘制边框, 使用canvas.drawRoundRect(rect,5,5,paint);这个方法就可以很简单的实现。
完整代码:
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.TextView;
import com.jbh.goldrush.Utils.LogUtils;
@SuppressLint("AppCompatCustomView")
public class BorderTextView extends TextView {
//绘制边框的的宽度
private int stroke_width = 1 ;
//默认边框的颜色黑色
private int stroke_color = Color.BLACK ;
public BorderTextView(Context context) {
this(context,null);
}
public BorderTextView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public BorderTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
this.setPadding(5,2,5,2);
this.setTextSize(8);
//绘制文字的颜色
this.setTextColor(stroke_color);
this.setGravity(Gravity.CENTER);
}
/**
* @param stroke_color
*/
public void setStrokeColor(int stroke_color) {
this.stroke_color = stroke_color;
invalidate();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int w= this.getMeasuredWidth() + stroke_width*2;
int h = this.getMeasuredHeight() + stroke_width*2;
LogUtils.LOG_V("w="+w);
LogUtils.LOG_V("w="+h);
setMeasuredDimension(w,h);
}
@Override
protected void onDraw(Canvas canvas) {
this.setTextColor(stroke_color);
Paint paint=new Paint();
paint.setStyle(Paint.Style.STROKE);
// 将边框设为黑色
paint.setColor(stroke_color);
paint.setStrokeWidth(2);
int left = stroke_width ;
int right = this.getWidth() - stroke_width;
int top= stroke_width ;
int bottom = this.getHeight() - stroke_width ;
RectF rect=new RectF(left,top,right,bottom);
canvas.drawRoundRect(rect,5,5,paint);
super.onDraw(canvas);
}
}