package com.example.a03_customview.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; /** * Created by yujie on 2017/11/30. */ public class CountView extends View implements View.OnClickListener { public CountView(Context context) { super(context); init(); } public CountView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public CountView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } /** * 控件初始化的方法 */ private void init() { //设置点击事件 this.setOnClickListener(this); } private int count = 0; @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = new Paint(); paint.setColor(Color.RED); paint.setStyle(Paint.Style.FILL); paint.setAntiAlias(true); canvas.drawCircle(300,300,200,paint);//圆 paint.setTextSize(100); paint.setColor(Color.BLACK); String text = count +""; //获取/测量文本的宽高,,,测量到的数据放到矩形边界里面 //start 从哪开始测量文字 end 到哪里结束 Rect rect = new Rect(); paint.getTextBounds(text,0,text.length(),rect); canvas.drawText(text,300-rect.width()/2,300+rect.height()/2,paint); } @Override public void onClick(View view) { count ++; postInvalidate();//重绘 } }
自定义View点击计算次数的demo
最新推荐文章于 2021-05-26 14:26:49 发布