在android中有的时候需求显示进度条,如果android自带的话,一是界面比较丑,二是有的需求满足不了,比如下图:
这种android自带的就没法实现了,今天就实现下这个自定义的控件
思路:
1:首先画一个圆
2:然后画一个弧,
关键代码:
package com.example.customprogressbar.ui;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
public class CustomProgressView extends View {
private Paint paint;
private int progress;
private MyThread myThread;
private boolean isStop = true;
public CustomProgressView(Context context, AttributeSet attrs,
int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
paint = new Paint();
}
public CustomProgressView(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
paint = new Paint();
}
public CustomProgressView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
}
public CustomProgressView(Context context) {
super(context);
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int center = getWidth()/2;
paint.setAntiAlias(true);
//画笔的宽度
paint.setStrokeWidth(20);
paint.setColor(Color.RED);
//设置画笔是空心的
paint.setStyle(Style.STROKE);
float radius = center-20/2;
canvas.drawCircle(center, center, radius, paint);
paint.setColor(Color.BLUE);
//设置画笔是空心的
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(20);
/**
* 画弧
* oval :指定圆弧的外轮廓矩形区域。
startAngle: 圆弧起始角度,单位为度。
sweepAngle: 圆弧扫过的角度,顺时针方向,单位为度,从右中间开始为零度。
useCenter: 如果为True时,在绘制圆弧时将圆心包括在内,通常用来绘制扇形。关键是这个变量,下
*/
RectF oval = new RectF(center-radius, center-radius, center+radius, center+radius);
canvas.drawArc(oval, 0, 360*progress/100, false, paint);
if(myThread==null){
myThread = new MyThread();
myThread.start();
}
paint.setColor(Color.GRAY);
//设置字体大小
paint.setTextSize(30);
paint.setStrokeWidth(1);
int percent = (progress*100)/100;
String content = percent+"%";
canvas.drawText(content, center-paint.measureText(content)/2, center+30/2, paint);
}
class MyThread extends Thread{
@Override
public void run() {
super.run();
while(isStop){
if(progress>=100){
progress = 0;
}else{
progress+=1;
}
postInvalidate();
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
isStop = false;
}
}
ok,代码没什么比较难懂的,在这不做解释