import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import java.util.Random; public class MyView extends View{ private final Paint paint; private final Context context; private int i=1234; public MyView(Context context) { this(context,null); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; this.paint = new Paint(); this.paint.setAntiAlias(true); //消除锯齿 this.paint.setStyle(Paint.Style.STROKE); //绘制空心圆 } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub int center = getWidth()/2; int innerCircle = dip2px(context, 83); //设置内圆半径 int ringWidth = dip2px(context, 5); //设置圆环宽度 //绘制内圆 this.paint.setARGB(155, 167, 190, 206); this.paint.setStrokeWidth(100); this.paint.setColor(Color.YELLOW); canvas.drawCircle(center,center, innerCircle, this.paint); //绘制文字 Paint textPaint = new Paint(); textPaint.setColor(Color.BLACK); textPaint.setStyle(Paint.Style.FILL); textPaint.setTextSize(25); canvas.drawText(String.valueOf(i),200,245,textPaint); // //绘制圆环 // this.paint.setARGB(255, 212 ,225, 233); // this.paint.setStrokeWidth(50); // this.paint.setColor(Color.BLUE); // canvas.drawCircle(center,center, innerCircle+1+ringWidth/2, this.paint); //绘制外圆 this.paint.setARGB(155, 167, 190, 206); this.paint.setStrokeWidth(80); this.paint.setColor(Color.RED); canvas.drawCircle(center,center, innerCircle+ringWidth, this.paint); super.onDraw(canvas); } /** * 根据手机的分辨率从 dp 的单位 转成为 px(像素) */ public static int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: //随机数的工具 Random random = new Random(); //做计算 i=1001+(int)(Math.random()*1000); // count++; invalidate(); break; } return super.onTouchEvent(event); } }
自定义view圆形之生成随机数改变
最新推荐文章于 2021-05-26 08:44:20 发布