核心代码
[code]@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);//圆心坐标centerX = getPivotX();centerY = getPivotY();//半径radius = getWidth() > getHeight() ? (float) getHeight() / 2 - 8 : (float) getWidth() / 2 - 8;//绘制圆paint.setColor(Color.BLACK);paint.setStyle(Paint.Style.STROKE);//画笔属性是空心圆paint.setStrokeWidth(4);//设置画笔粗细canvas.drawCircle(centerX, centerY, radius, paint);//绘制中心黑点paint.setStyle(Paint.Style.FILL);canvas.drawCircle(centerX, centerY, radius / 20, paint);//绘制中心点//绘制盘表上的字体paint.setTextSize(48);paint.setStrokeWidth(1);//设置画笔粗细canvas.drawText(text, centerX - (float) getTextWidth(paint, text) / 2, centerY + radius / 5, paint);//绘制刻度线for (int i = 0; i <= 100; i++) {//刻度3.3度,+90是要从第三象限开始画startC = (float) 3.3 * i + 90;//判断角的大小处于第几象限int sth = 1;if (startC % 360 > 180 && startC % 360 < 360) {sth = -1;}//终点坐标float lineToX = (float) (centerX + Math.cos(Math.toRadians(-startC)) * (radius - radius / 20));//利用数学cos求x坐标float lineToY = (float) (centerY + sth * Math.abs(Math.sin(Math.toRadians(-startC))) * (radius - radius / 20));//sin函数求y坐标//开始坐标float startX;float startY;if (i % 10 == 0) {startX = lineToX - (float) (Math.cos(Math.toRadians(-startC)) * (radius / 4));startY = lineToY - (float) (sth * Math.abs(Math.sin(Math.toRadians(-startC))) * (radius / 4));//绘制刻度线上的字体paint.setTextSize(32);paint.setStrokeWidth(1);//设置画笔粗细//刻度线上的字体坐标float textX = lineToX - (float) (Math.cos(Math.toRadians(-startC)) * (radius / 3));//设置字体的位置float textY = lineToY - (float) (sth * Math.abs(Math.sin(Math.toRadians(-startC))) * (radius / 3));//设置字体的位置canvas.drawText(String.valueOf(i), textX - radius / 20, textY + radius / 20, paint);} else {startX = lineToX - (float) (Math.cos(Math.toRadians(-startC)) * (radius / 5));startY = lineToY - (float) (sth * Math.abs(Math.sin(Math.toRadians(-startC))) * (radius / 5));}//红色区域if (i == 90) {initRectF();paint.setStyle(Paint.Style.STROKE);//画笔属性是空心圆paint.setColor(Color.RED);paint.setStrokeWidth(radius / 5);canvas.drawArc(rectF, startC, 33, false, paint);}//绘制刻度paint.setStyle(Paint.Style.FILL);//画笔实心paint.setColor(Color.BLACK);paint.setStrokeWidth(4);//设置画笔粗细canvas.drawLine(startX, startY, lineToX, lineToY, paint);}//绘制指针paint.setColor(Color.BLACK);/* canvas.restore();canvas.save();canvas.translate(canvas.getWidth()/2, r);*///根据参数得到旋转角度canvas.rotate(changeRadius, centerX, centerY);//绘制三角形形成指针Path path = new Path();path.moveTo(centerX - radius / 40, centerY);path.lineTo(centerX + radius / 40, centerY);path.lineTo(centerX, centerY + radius / 4 * 3);path.lineTo(centerX - radius / 40, centerY);path.close();canvas.drawPath(path, paint);}
指针摆动动画
[code]public void setRadius(float radius) {this.oldRadius = this.per;this.per = radius * (float) 3.3;ValueAnimator va = ValueAnimator.ofFloat(oldRadius, per);va.setDuration(1000);va.setInterpolator(new OvershootInterpolator());va.addUpdateListener(animation -> {changeRadius = (float) animation.getAnimatedValue();invalidate();});va.start();}
效果图