public class BatteryView extends View { private int mMargin = 15; //电池内芯与边框的距离 private int mBoder = 12; //电池外框的宽带 private int mWidth = 210; //总长 private int mHeight = 120; //总高 private int mHeadWidth = 18; //头部宽度 private int mHeadHeight = 30; //头部高度 private RectF mMainRect; //外边框 private RectF mHeadRect; //头部边框 private float mRadius = 12f; //圆角 private float mPower; public BatteryView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(); } public BatteryView(Context context, AttributeSet attrs) { super(context, attrs); initView(); } public BatteryView(Context context) { super(context); initView(); } private void initView() { mHeadRect = new RectF(mWidth - mHeadWidth, (mHeight - mHeadHeight)/2, mWidth, (mHeight + mHeadHeight)/2); float left = mHeadRect.width(); float top = mBoder; float right = mWidth - mHeadWidth; float bottom = mHeight-mBoder; mMainRect = new RectF(left, top, right, bottom); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint1 = new Paint(); //画外框 paint1.setStyle(Paint.Style.STROKE); //设置空心矩形 paint1.setStrokeWidth(mBoder); //设置边框宽度 paint1.setColor(Color.parseColor("#ff0000")); canvas.drawRoundRect(mMainRect, mRadius, mRadius, paint1); //画电池头 paint1.setStyle(Paint.Style.FILL); //实心 paint1.setColor(Color.parseColor("#00ff00")); canvas.drawRect(mHeadRect, paint1); //画电池芯 Paint paint = new Paint(); paint.setColor(Color.parseColor("#0000ff")); int width = (int) (mPower * (mMainRect.width() - mMargin*2)); int left = (int) (mMainRect.left + mMargin); int right = (int) (mMainRect.left + mMargin + width); int top = (int) (mMainRect.top + mMargin); int bottom = (int) (mMainRect.bottom - mMargin); Rect rect = new Rect(left,top,right, bottom); canvas.drawRect(rect, paint); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(mWidth, mHeight); } public void setPower(float power) { mPower = power; invalidate(); }}复制代码
外部调用:
复制代码
private BatteryView batteryView; private float power; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 0: batteryView.setPower(power += 0.1); if (power >= 1) { power = 0; } break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); batteryView = (BatteryView) findViewById(R.id.id_batteryView); batteryView.setPower(0.1f); //模拟充电过程 new Timer().schedule(new TimerTask() { @Override public void run() { mHandler.sendEmptyMessage(0); } }, 0, 100); }}复制代码