一、概述
今天接着研究paint画笔,实现圆环百分比进度变化效果,效果图如下:
二、思路分析
这个效果其实和前面的qq计步器实现思路差不多,那个是两个圆弧,这个里面是不动的圆形,外面是圆弧。
2.1自定义属性
自定义属性包含内圆画笔的颜色,画笔描边的粗细,外面圆弧的画笔颜色,里面中间百分比文字的大小和颜色。
attrs文件
自定义类构造函数
//获取属性
public CircleProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.CircleProgressView);
mInnerColor = a.getColor(R.styleable.CircleProgressView_innerCicleColor,mInnerColor);
mOutColor = a.getColor(R.styleable.CircleProgressView_outCicleColor,mOutColor);
mRoundWidth = (int)a.getDimension(R.styleable.CircleProgressView_roundWidth,dp2px(mRoundWidth));
mTextSize = a.getDimensionPixelSize(R.styleable.CircleProgressView_progressTextSize,sp2px(mTextSize));
a.recycle();
mInnerPaint = new Paint();
mInnerPaint.setColor(mInnerColor);
mInnerPaint.setAntiAlias(true); //抗锯齿
mInnerPaint.setStrokeWidth(mRoundWidth);
mInnerPaint.setStyle(Paint.Style.STROKE); //空心圆
mOutPaint = new Paint();
mOutPaint.setColor(mOutColor);
mOutPaint.setAntiAlias(true); //抗锯齿
mOutPaint.setStrokeWidth(mRoundWidth);
mOutPaint.setStyle(Paint.Style.STROKE); //空心圆
mTextPaint = new Paint();
mTextPaint.setTextSize(mTextSize);
mTextPaint.setColor(mTextColor);
}
2.2在ondraw方法中绘制
//绘制
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//绘制内圆
int center = getWidth()/2;
canvas.drawCircle(center,center,center-mRoundWidth/2,mInnerPaint);
//绘制外圆
RectF rectF = new RectF(mRoundWidth/2,mRoundWidth/2,getWidth()-mRoundWidth/2,getHeight()-mRoundWidth/2);
if (mCurrentProgress == 0){
return;
}
float percent = (float)mCurrentProgress/mMax;
canvas.drawArc(rectF,0,percent*360,false,mOutPaint); //false 表示不包括圆心
//绘制文字
String textString = ((int)(percent*100))+"%";
// String textString = (mMax - (mCurrentProgress-1))+"";
Rect bounds = new Rect();
mTextPaint.getTextBounds(textString,0,textString.length(),bounds);
int dy = (mTextPaint.getFontMetricsInt().bottom-mTextPaint.getFontMetricsInt().top)/2-mTextPaint.getFontMetricsInt().bottom;
int baseLine = getHeight()/2 + dy;
canvas.drawText(textString,getWidth()/2-bounds.width()/2,baseLine,mTextPaint);
}
对圆的半径的计算不理解的可以参考这边文章:
Canvas drawCircle Rect边框问题
onmeasure方法就不介绍了,前面说了很多了。
2.3暴露给用户方法动态改变百分比的值
//暴露给外面调用 设置当前值 不断调用ondraw方法
public synchronized void setCurrentProgress(int currentProgress) {
this.mCurrentProgress = currentProgress;
invalidate();
}
在mainActivity中用设置属性动画,监听值的变化,调用此方法,绘制界面:
circleProgressView.setMax(4000);
ValueAnimator objectAnimator = ObjectAnimator.ofFloat(1,4000);
objectAnimator.setDuration(5000);
objectAnimator.start();
objectAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float progress = (float) animation.getAnimatedValue();
circleProgressView.setCurrentProgress((int) progress);
}
});
三、结语
当然,这个效果也可以扩展,你可以做成别的效果,例如倒计时,代码稍微改动下就行了。分析完毕,代码地址:
http://pan.baidu.com/s/1o80TQm2