Android自己定义View之仪表盘
Posted cxchanpin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android自己定义View之仪表盘相关的知识,希望对你有一定的参考价值。
新建项目,新建DashBoardView
继承自View
实现OnGlobalLayoutListener
接口,并重写OnDraw
方法。
使用OnGlobalLayoutListener
接口须要重写onGlobalLayout
方法。在这种方法中我们将获取View的宽高。
新建例如以下变量:
private Context mContext;
private Paint mCirclePaint,mDegreePaint,mHourPaint,mMinPaint;
private int mViewWidth,mViewHeight;
初始化这些变量:
public void init(Context context){
mContext = context;
mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mDegreePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mHourPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mMinPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCirclePaint.setAntiAlias(true);
mCirclePaint.setStrokeWidth(5);
mCirclePaint.setStyle(Paint.Style.STROKE);
mHourPaint.setStrokeWidth(20);
mMinPaint.setStrokeWidth(10);
getViewTreeObserver().addOnGlobalLayoutListener(this);
}
onGlobalLayout
中初始化DashBoardView
宽高:
@Override
public void onGlobalLayout() {
mViewHeight = getHeight();
mViewWidth = getWidth();
}
在onDraw方法中加入例如以下绘制代码:
/*
* 画表盘圆形
* */
canvas.drawCircle(mViewWidth/2,mViewHeight/2,mViewWidth/2,mCirclePaint);
/*
* 画刻度
* */
for (int i=0;i<24;i++){
if(i==0 || i==6 || i==12 || i==18){
/*
* 画整点刻度
* */
mDegreePaint.setStrokeWidth(5);
mDegreePaint.setTextSize(30);
canvas.drawLine(mViewWidth/2,mViewHeight/2-mViewWidth/2,mViewWidth/2,mViewHeight/2-mViewWidth/2+60,mDegreePaint);
String degree = String.valueOf(i);
canvas.drawText(degree,mViewWidth/2-mDegreePaint.measureText(degree)/2,mViewHeight/2-mViewWidth/2+90,mDegreePaint);
}else{
mDegreePaint.setStrokeWidth(3);
mDegreePaint.setTextSize(15);
canvas.drawLine(mViewWidth/2,mViewHeight/2-mViewWidth/2,mViewWidth/2,mViewHeight/2-mViewWidth/2+30,mDegreePaint);
String degree = String.valueOf(i);
canvas.drawText(degree,mViewWidth/2-mDegreePaint.measureText(degree)/2,mViewHeight/2-mViewWidth/2+90,mDegreePaint);
}
/*
* 通过旋转画布来画好全部的刻度
* */
canvas.rotate(15,mViewWidth/2,mViewHeight/2);
}
/*
* 画指针
* */
mHourPaint.setStrokeWidth(20);
mMinPaint.setStrokeWidth(10);
canvas.save();
canvas.translate(mViewWidth/2,mViewHeight/2);
canvas.drawLine(0,0,100,100,mHourPaint);
canvas.drawLine(0,0,100,200,mMinPaint);
canvas.restore();
至此我们就完毕了一个仪表盘的绘制。效果图例如以下:
完整代码下载:完整项目
以上是关于Android自己定义View之仪表盘的主要内容,如果未能解决你的问题,请参考以下文章