项目当中的UI有这样的一个控件,显示U盘的总容量和已经使用的容量
自己根据自定义控件的开发流程做了一个简单的控件
注:控件还有一些小问题,右边的半圆不知道怎么绘制,只能在超过矩形框的时候一次性全部绘制了,有没有大神指导一下,右边的半圆按容量增加一点点绘制
/**
* Created by Orange on 2017/5/24.
* <p>
* 显示U盘容量的控件
*/
public class CapacityView extends View {
//总容量100
private static final int TOTAL_CAPACITY = 100;
//总容量画笔
private Paint greyPaint;
//已使用容量画笔
private Paint greenPaint;
//控件高
private int mHeight;
//控件宽
private int mWidth;
//已使用容量的宽
private int cWidth = 0;
public CapacityView(Context context) {
super(context);
}
public CapacityView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
greenPaint = new Paint();
greenPaint.setAntiAlias(true);
greenPaint.setColor(getResources().getColor(R.color.colorAccent));
greyPaint = new Paint();
greenPaint.setAntiAlias(true);
greyPaint.setColor(getResources().getColor(R.color.colorPrimary));
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
mHeight = h;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawBack(canvas);
drawReal(canvas);
}
private void drawBack(Canvas canvas) {
RectF rectF1 = new RectF(0, 0, mHeight, mHeight);
canvas.drawArc(rectF1, 90, 180, true, greyPaint);
RectF rectF2 = new RectF(mWidth - mHeight, 0, mWidth, mHeight);
canvas.drawArc(rectF2, -90, 180, true, greyPaint);
RectF rectF3 = new RectF(mHeight / 2, 0, mWidth - mHeight / 2, mHeight);
canvas.drawRect(rectF3, greyPaint);
}
private void drawReal(Canvas canvas) {
if (cWidth <= mHeight / 2) {
float x = ((float) mHeight - cWidth * 2) / mHeight;
float a = (float) (Math.acos(x) * 180 / Math.PI);
RectF rectF1 = new RectF(0, 0, mHeight, mHeight);
canvas.drawArc(rectF1, 180 - a, 2 * a, false, greenPaint);
Log.d("********", a + "");
} else if (cWidth > mHeight / 2 && cWidth <= (mWidth - mHeight / 2)) {
RectF rectF1 = new RectF(0, 0, mHeight, mHeight);
canvas.drawArc(rectF1, 90, 180, true, greenPaint);
RectF rectF3 = new RectF(mHeight / 2, 0, cWidth, mHeight);
canvas.drawRect(rectF3, greenPaint);
} else {
RectF rectF1 = new RectF(0, 0, mHeight, mHeight);
canvas.drawArc(rectF1, 90, 180, true, greenPaint);
RectF rectF2 = new RectF(mWidth - mHeight, 0, mWidth, mHeight);
canvas.drawArc(rectF2, -90, 180, true, greenPaint);
RectF rectF3 = new RectF(mHeight / 2, 0, mWidth - mHeight / 2, mHeight);
canvas.drawRect(rectF3, greenPaint);
}
}
/**
* 在你的activity内调用,设置u盘已使用的容量
* @param w 0~100的值,即使用的百分比
*/
public void setcWidth(int w) {
this.cWidth = w;
cWidth = (int) (((float) cWidth) / TOTAL_CAPACITY * mWidth);
invalidate();
}