自适应大小的进度条
根据View宽度来绘制进度,极简风格。
先在onDraw方法里获取View的宽度
int width = getWidth();
int height = getHeight();
重要的一部分来了,计算绘制时所需宽度
//View宽度的百分之一
float bfzy = (float) width / 100;
//绘制进度所需宽度,mProgress为进度值
int sxkd = (int) (bfzy * mProgress);
这里是全部代码:
import android.content.Context;
import android.graphics.*;
import android.view.View;
public class MyProgressView extends View {
//定义进度条的画笔
private Paint mPaint;
//进度
private float mProgress;
//前景色
private int ForegroundColor;
//背景色
private int BackgroundColor;
public MyProgressView(Context context) {
super(context);
mProgress = 0f;
mPaint = new Paint();
ForegroundColor = 0xff888888;
BackgroundColor = 0Xfff0f0f0;
}
@Override
public void onDraw(Canvas canvas) { //设置背景色
mPaint.setColor(BackgroundColor);
Rect dst = new Rect();
dst.left = 0;
dst.top = 0;
dst.right = getWidth();
dst.bottom = getHeight();
//画背景
canvas.drawRect(dst, mPaint);
if (mProgress > 0) {
//进度值 > 0 时绘制
float bfzy = (float) getWidth() / 100;
int sxkd = (int) (bfzy * mProgress);
//设置前景色
mPaint.setColor(ForegroundColor);
Rect dst1 = new Rect(); dst1.left = 0;
dst1.top = 0;
dst1.right = sxkd;
dst1.bottom = getHeight();
//画进度
canvas.drawRect(dst1, mPaint);
}
}
//设置前景色
public void setForegroundColor(int co) {
this.ForegroundColor = co;
invalidate();
}
//设置背景色
public void setBackgroundColor(int co) {
this.BackgroundColor = co;
invalidate();
}
//获取前景色
public int getForegroundColor() {
return this.ForegroundColor;
}
//获取背景色
public int getBackgroundColor() { return this.BackgroundColor;
}
//设置当前进度值
public void setProgress(float pr) {
this.mProgress = pr;
invalidate();
}
//获取进度值百分比
public float getProgress() {
return this.mProgress;
}
}