本文主要是介绍使用Canvas绘制圆形表盘,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
绘制圆形表盘
public class Clock extends View {private int mHeight, mWidth;public Clock(Context context) {super(context);}public Clock(Context context, AttributeSet attrs) {super(context, attrs);}public Clock(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);}@Overrideprotected void onDraw(Canvas canvas) {// 获取宽高参数mWidth = getMeasuredWidth();mHeight = getMeasuredHeight();// 画外圆Paint paintCircle = new Paint();paintCircle.setStyle(Paint.Style.STROKE);paintCircle.setAntiAlias(true);paintCircle.setStrokeWidth(5);canvas.drawCircle(mWidth / 2,mHeight / 2, mWidth / 2, paintCircle);// 画刻度Paint painDegree = new Paint();paintCircle.setStrokeWidth(3);for (int i = 0; i < 24; i++) {// 区分整点与非整点if (i == 0 || i == 6 || i == 12 || i == 18) {painDegree.setStrokeWidth(5);painDegree.setTextSize(30);canvas.drawLine(mWidth / 2, mHeight / 2 - mWidth / 2,mWidth / 2, mHeight / 2 - mWidth / 2 + 60,painDegree);String degree = String.valueOf(i);canvas.drawText(degree,mWidth / 2 - painDegree.measureText(degree) / 2,mHeight / 2 - mWidth / 2 + 90,painDegree);} else {painDegree.setStrokeWidth(3);painDegree.setTextSize(15);canvas.drawLine(mWidth / 2, mHeight / 2 - mWidth / 2,mWidth / 2, mHeight / 2 - mWidth / 2 + 30,painDegree);String degree = String.valueOf(i);canvas.drawText(degree,mWidth / 2 - painDegree.measureText(degree) / 2,mHeight / 2 - mWidth / 2 + 60,painDegree);}// 通过旋转画布简化坐标运算canvas.rotate(15, mWidth / 2, mHeight / 2);}// 画圆心Paint paintPointer = new Paint();paintPointer.setStrokeWidth(30);canvas.drawPoint(mWidth / 2, mHeight / 2, paintPointer);// 画指针Paint paintHour = new Paint();paintHour.setStrokeWidth(20);Paint paintMinute = new Paint();paintMinute.setStrokeWidth(10);canvas.save();canvas.translate(mWidth / 2, mHeight / 2); //平移画布canvas.drawLine(0, 0, 100, 100, paintHour);canvas.drawLine(0, 0, 100, 200, paintMinute);canvas.restore(); //恢复画布状态 我们取出的是最后一个存入栈中的canvas实例 }
}
这篇关于使用Canvas绘制圆形表盘的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!