//第一步 写个MyView类继承View,重写三个构造方法。
//default Size ,measure Spec,mode,Measured,Dimension,canvas
//默认大小、测量规格、模式、测量值、尺寸、画布
public class MyView extends View {
//第一个是在java代码里用这个View时调用
public MyView(Context context) {
super(context);
}
//第二个是xml使用这个View时调用的,通过AttrbuteSet把这个属性和一些参数传给View
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
//第三个是主题风格信息,会从xml带入,xml加载的时候能执行一个特定的风格
public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width=300;
int height=300;
//设置测量值的尺寸,传宽和高
setMeasuredDimension(width,height);
}
//调用父View的onDraw函数,因为View这个类帮我们实现了一些
// 基本的而绘制功能,比如绘制背景颜色、背景图片等
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//获得宽度半径
int w2 = getMeasuredWidth() / 2;
//获得圆心的横向坐标点 ,通过左View开始点+宽度半径=圆心
int yuanxin1 = getLeft() + w2;
//获得圆心的纵向坐标点,通过上View开始点+宽度半径=圆心,因为尺寸是个300x300的正方形,所以同样获得宽度半径就行
int yuanxin2 = getTop() + w2;
//创建画笔对象
Paint paint = new Paint();
//通过画笔设置颜色为蓝色
paint.setColor(Color.BLUE);
//使用画布绘制上去,drawCircle方法是画圆形
canvas.drawCircle(yuanxin1,yuanxin2,w2,paint);
}
}
//第二步 布局:
<com.example.hasee.a91zidingyiview.MyView
android:background="#ff0000"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
//---------------------------------------------------------------完-----------------------------------------------------------------------------