1.先新建一个类继承View方法
package com.example.ll.canvas;
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.view.MotionEvent;
import android.view.View;
/**
* Created by ll on 2018/3/30.
*/
public class MyView extends View {
private Paint paint = new Paint();
private int num = 0;
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//圆·的·颜色
paint.setColor(Color.BLUE);
//抗锯齿设定
paint.setAntiAlias(true);
//圆的位置判断、半径
canvas.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 4, paint);
//画笔颜色不能重复,不然看不出来
paint.setColor(Color.RED);
//字体大小
paint.setTextSize(50);
//文字不像圆,需要微调
canvas.drawText(num + "", getWidth() / 2 - 15, getHeight() / 2 + 25, paint);
}
//点击事件
@Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction()!=MotionEvent.ACTION_DOWN&&event.getAction()!=MotionEvent.ACTION_MOVE){
//实现自加
num++;
//重新调用上面onDraw方法
invalidate();
}
return super.onTouchEvent(event);
}
}
2.最后在main函数中的xml中加上自定义View即可
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ll.canvas.MainActivity">
<com.example.ll.canvas.MyView
android:id="@+id/ccm"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>