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之仪表盘_第1张图片

完整代码下载:完整项目

你可能感兴趣的:(android)