package com.example.desktop_77ma6t9.kaoshi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class Myview extends View {
private static final String TAG = "Myview";
public Myview(Context context) {
this(context,null);
}
public Myview(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public Myview(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
* onDraw 最终要的方法
* @param canvas 画布
*/
protected void onDraw(Canvas canvas){
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.RED);
//画笔粗细
paint.setFakeBoldText(true);
//描边
// paint.setStyle(Paint.Style.STROKE);
//画圆
canvas.drawCircle(50,50,50,paint);
//定义画笔
Paint paint1 = new Paint(Paint.ANTI_ALIAS_FLAG);
//填充
paint1.setFakeBoldText(true);
//画笔颜色
paint1.setColor(Color.WHITE);
//描边
// paint1.setStyle(Paint.Style.STROKE);
canvas.drawCircle(50,50,30,paint1);
// Path path = new Path();
// path.moveTo(0,0);
// path.lineTo(50,50);
// path.lineTo(0,100);
// paint.setColor(Color.GREEN);
// canvas.drawPath(path,paint);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//
int widthmode = MeasureSpec.getMode(widthMeasureSpec);
//控件的宽度 单位像素
int widthsize = MeasureSpec.getSize(widthMeasureSpec);
Log.i("TAG","onMeasure : widthmode is"+widthmode+"and widthsize is"+widthsize);
//
int heightmode = MeasureSpec.getMode(heightMeasureSpec);
//控件的高度 单位像素
int heightsize = MeasureSpec.getSize(heightMeasureSpec);
Log.i("TAG","onMeasure : heightmode is"+heightmode+"and heightsize is"+heightsize);
//判断宽度 的模式
//测量的三种模式
switch (widthmode){
// 有多大占多大,一般是wrap_content
case MeasureSpec.AT_MOST:
Log.i(TAG, "widthmode is AT_MOST");
break;
// 一般我们不怎么用,主要给系统提供了一些设置
case MeasureSpec.UNSPECIFIED:
Log.i(TAG, "widthmode is UNSPECIFIED");
break;
// 精确值,两种情况下模式是EXACTLY,
// 一个就是设置一个固定数值,另一种情况就是设置值是match_parent
case MeasureSpec.EXACTLY:
Log.i(TAG, "widthmode is EXACTLY");
break;
}
switch (heightmode){
case MeasureSpec.AT_MOST:
Log.i(TAG, "heightmode is AT_MOST");
break;
case MeasureSpec.UNSPECIFIED:
Log.i(TAG, "heightmode is UNSPECIFIED");
break;
case MeasureSpec.EXACTLY:
Log.i(TAG, "heightmode is EXACTLY");
break;
}
// 设置View最终的宽高
setMeasuredDimension(150,100);
}
}
//布局
<com.example.desktop_77ma6t9.kaoshi.Myview
android:layout_width="match_parent"
android:background="#f0f0f5"
android:layout_height="wrap_content" />
自定View之自己绘图_两个重要方法onDraw/onMeasure设置View最终宽高
最新推荐文章于 2021-05-26 13:00:39 发布