public class BatteryLevel extends View { private Paint mPaint = new Paint(); private double powerLevel = 0.56;//默认剩余电量 private int bodyWidth = ScreenUtils.dp2px(MyApplication.mContext, 24);//电池体宽 private int bodyHeight = ScreenUtils.dp2px(MyApplication.mContext, 12);//电池体高 private int headWidth = ScreenUtils.dp2px(MyApplication.mContext, 1.5f);//电池头宽 private int space = ScreenUtils.dp2px(MyApplication.mContext, 1.0f);//电量区域和电池体边的间隙 private RectF rectBatteryBody = new RectF(0, 0, bodyWidth, bodyHeight); private RectF rectBatteryHead = new RectF(bodyWidth, (float) CalcUtils.div(bodyHeight, 4, 2), bodyWidth + headWidth, (float) CalcUtils.div(bodyHeight * 3, 4, 2)); public BatteryLevel(Context context) { super(context); } public BatteryLevel(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public BatteryLevel(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // 获取宽-测量规则的模式和大小 int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); // 获取高-测量规则的模式和大小 int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); // 设置wrap_content的默认宽 / 高值 int mWidth = bodyWidth + headWidth; int mHeight = bodyHeight; // 当模式是AT_MOST(即wrap_content)时设置默认值 if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) { setMeasuredDimension(mWidth, mHeight); } else if (widthMode == MeasureSpec.AT_MOST) { setMeasuredDimension(mWidth, heightSize); } else if (heightMode == MeasureSpec.AT_MOST) { setMeasuredDimension(widthSize, mHeight); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawColor(0x888888); //画电池体 mPaint.reset(); mPaint.setAntiAlias(true); mPaint.setColor(Color.WHITE); mPaint.setStyle(Paint.Style.STROKE); float round = ScreenUtils.dp2px(MyApplication.mContext, 1); canvas.drawRoundRect(rectBatteryBody, round, round, mPaint); //画电池头 mPaint.setStyle(Paint.Style.FILL); canvas.drawRoundRect(rectBatteryHead, round, round, mPaint); //画电量 if (powerLevel <= 0.3) { mPaint.setColor(Color.RED); } canvas.drawRect(space, space, (float) (CalcUtils.mul((bodyWidth - 2 * space), powerLevel) + space), bodyHeight - space, mPaint); } /** * 设置电量 * * @param level 当前电量值 */ public void setPowerLevel(int level) { powerLevel = level < 0 ? 0 : CalcUtils.div(level, 100, 2); invalidate(); } }
mBsPower.setPowerLevel(level);