Android自己定义控件–圆形进度条(中间有图diao)

智能家居越来越流行,在智能家居中我们常要表现一些数据的百分比 圆形度条中间加个图是一种很流行的自己定义View

1.第一步 你首先须要对类进行继承View

public class CircleProgressImageView extends View

2.第二步 要实现三个构造方法 而且前面少參数的调用当前多參数的构造方法

public CircleProgressImageView(Context context) { this(context,null);}public CircleProgressImageView(Context context, AttributeSet attrs) { this(context, attrs,0);}public CircleProgressImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context,attrs,defStyleAttr);}

3.第三步:取自己定义属性 而且对画笔 等进行初始化

private void init(Context context, AttributeSet attrs, int defStyleAttr) { this.context=context; /**  * 获取自己定义属性  */  TypedArray a=context.obtainStyledAttributes(attrs,R.styleable.CIRCLEPROGRESSIMAGEVIEWATTRS); bitmap=a.getResourceId(R.styleable.CIRCLEPROGRESSIMAGEVIEWATTRS_imagers,R.mipmap.ic_launcher); /**  * 把图片资源转为Bitmap对象  */  drawBitmap=BitmapFactory.decodeResource(context.getResources(),bitmap); /**  * 初始化RectF对象  */  mRectF=new RectF(); mPaint=new Paint(); mPaint.setAntiAlias(true);}

4.第四步:是在
onMeasure
方法中对height 和width进行处理

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); /**  * 获取当前View的宽高  */  width=this.getWidth(); height=this.getHeight(); /**  * 对其左右上下进行处理  */  mRectF.left=mCircleStoreWidth/2; mRectF.top=mCircleStoreWidth/2; mRectF.right=width-mCircleStoreWidth/2; mRectF.bottom=width-mCircleStoreWidth/2;}

5.这时候我们须要对ondraw()方法进行绘制了

protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawColor(Color.TRANSPARENT); //画圆北京 mPaint.setColor(getResources().getColor(R.color.orange)); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(mCircleStoreWidth); canvas.drawArc(mRectF,-90,360,false,mPaint); /**  * 画圆弧的进度显示  */  mPaint.setColor(getResources().getColor((R.color.gray))); canvas.drawArc(mRectF,-90,((float) mProcessValue/mMaxProcessValue)*360,false,mPaint); Log.d(TAG,((float) mProcessValue/mMaxProcessValue)*360+""); /**  * 画中间的图  */  float imageLeft=width/2-drawBitmap.getWidth()/2; float imageTop=height/2-drawBitmap.getHeight()/2; canvas.drawBitmap(drawBitmap,imageLeft,imageTop,mPaint);}

这样我们就实现了一个很好看和简单的自己定义View 自己定义属性參考其它文章 这里就不细说了 

可是这个View是不会转动的 仅仅有通过MainActivity在线程中设置setmProcessValue(processValue)调用改变值就能够转动了。

源代码下载


相关文章