標籤:ffffff extend rect data pop 進度顯示 etop 初始化 awb
智能家居越來越流行,在智能家置中我們常要表現一些資料的百分比 圓形度條中間加個圖是一種很流行的自己定義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)調用改變值就能夠轉動了。
原始碼下載
Android自己定義控制項--圓形進度條(中間有圖diao)