100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Android自定义控件--圆形进度条(中间有图diao)

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

时间:2021-11-26 14:07:34

相关推荐

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)调用改变值就可以转动了。

源码下载

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。