自定义View学习之路之进度条
android高阶之路自定义view必不可少,勤做笔记方便自己 帮助他人,人生在勤,不索何获。废话少说先上图
大致就是这么个样子,卡路里进度条,下面看代码
private float progress = 0;
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
public static final float RADIUS = Utils.dpToPixel(100);
public static final String str = "卡路里";
RectF rectF = new RectF();
Rect rect = new Rect();
public float getProgress() {
return progress;
}
public void setProgress(float progress) {
this.progress = progress;
invalidate();
}
public CustomBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
{
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(Utils.dpToPixel(20));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float cx = getWidth() / 2;
float cy = getHeight() / 2;
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(Utils.dpToPixel(20));
paint.setColor(Color.BLUE);
rectF.set(cx - RADIUS,cy - RADIUS,cx + RADIUS ,cy + RADIUS);
canvas.drawArc(rectF,135,progress*2.7f,false,paint);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
paint.getTextBounds(str,0,str.length(),rect);
int offset = (rect.top + rect.bottom) / 2;
canvas.drawText(str+(int) progress +"%",cx,cy-offset,paint);
}
核心代码就这多,动画用的是ObjectAnimator
ObjectAnimator animator = ObjectAnimator.ofFloat(mView, "progress", 100);
animator.setDuration(1000);
animator.start();
dpToPixel是个工具类dp转px,这里也贴出来
public static float dpToPixel(float dp){
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
return dp * metrics.density;
}
这里特别记录一下绘制文字的时候drawText 的 y 轴为什么不直接用getWidth() / 2,而是要减去一个offset呢,其实getWidth() / 2也可以,但是对于一个有强迫症的人来说我怎么看它不都不像是在正中间。查过资料发现这个绘制文字坐标有点意思,(此时灵魂画师上线)画了张图来有助于理解
大致就是这个意思,还看得过去。希望可以帮助到有需要的人,也练习练习自己的语言组织能力,如有写的不好的地方还请指教,小兵一定洗耳恭听。