效果图:
代码:
package com.example.lenovo.mydemo.myViewDemo; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.Log; import android.view.View; import com.example.lenovo.mydemo.R; /** * Created by lenovo on 2018/7/2. */ public class MyView_1 extends View { private final String TAG = "MyView_1"; private float radius; private int color; private Paint mPaint; public MyView_1(Context context) { super(context); } public MyView_1(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public MyView_1(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Log.e(TAG, "onDraw_radius:"+radius); /* 用多线段画矩形(也可以直接drawRect画矩形) */ //创建画笔 关于画笔可以也可以不创建多个画笔使用paint1.reset();来重置画笔 Paint paint1 = new Paint(); //给画笔添加颜色 paint1.setColor(Color.RED); //设置画笔宽度 paint1.setStrokeWidth(10); //设置画笔转角(两个线相交的点)风格 paint1.setStrokeJoin(Paint.Join.MITER); //设置抗锯齿 paint1.setAntiAlias(true); float[] f = new float[]{ 0,0,//第一条线的起始点 getWidth(),0,//第一条线的终点 getWidth(),0,//第二条线的起始点 getWidth(),getHeight(),//第二条线的终点 getWidth(),getHeight(),//同上 0,getHeight(), 0,getHeight(), 0,0}; //在画布上画多线段,添加坐标和画笔 canvas.drawLines(f,paint1); /* 画圆 */ //创建画笔 Paint paint2 = new Paint(); //设置画笔颜色 paint2.setColor(getResources().getColor(R.color.colorPrimary)); //设置画笔宽度 paint2.setStrokeWidth(10); //抗齿距 paint2.setAntiAlias(true); //画空心圆 如果不设置默认是实心圆 另外2个参数是 FILL 和 FILL_AND_STROKE 分别都实心圆 paint2.setStyle(Paint.Style.STROKE); //画圆形 传入X坐标Y坐标(2个坐标合起来做中心点),然后是半径200加画笔 canvas.drawCircle(getWidth()/2,getHeight()/2,200,paint2); /* 画文字 */ Paint paint3 = new Paint(); /* ----------- 字体类型 ------------- * Typeface.DEFAULT //常规字体类型 * Typeface.DEFAULT_BOLD //黑体字体类型 * Typeface.MONOSPACE //等宽字体类型 * Typeface.SANS_SERIF //sans serif字体类型 * Typeface.SERIF //serif字体类型 ------------ 字体风格 --------------- * * Typeface.BOLD //粗体 * Typeface.BOLD_ITALIC //粗斜体 * Typeface.ITALIC //斜体 * Typeface.NORMAL //常规 */ Typeface typeface = Typeface.create(Typeface.DEFAULT,Typeface.NORMAL); //导入字体类型和风格 paint3.setTypeface(typeface); //设置字体大小 paint3.setTextSize(50); //设置线宽 paint3.setStrokeWidth(5); //设置颜色 paint3.setColor(Color.RED); //设置文字居中 paint3.setTextAlign(Paint.Align.CENTER); canvas.drawText("你好",getWidth()/2,getHeight()/2,paint3); } }