android 自定义View绘制电池电量(电池内带数字显示)
16lz
2021-01-26
最新公司需要一个电池内带数字的显示电池电量需求,百度了一下。参考下面这篇文章写的Android自定义View之电池电量显示。
增加了里面电池电量数字显示,还有就是一个屏幕适配。不管屏幕分辨率基本都能适配。直接上代码吧。
import android.annotation.SuppressLint;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.RectF;import android.util.AttributeSet;import android.util.DisplayMetrics;import android.view.View;public class DrawView1 extends View { private float percent = 0f; // 电池电量外面的大白框 Paint paint = new Paint(); // 电池电量里面的绿色 Paint paint1 = new Paint(); // 电池头部 Paint paint2 = new Paint(); public DrawView(Context context, AttributeSet set) { super(context, set); // 去锯齿 paint.setAntiAlias(true); paint.setStyle(Paint.Style.FILL); paint1.setAntiAlias(true); paint1.setStyle(Paint.Style.STROKE); paint1.setStrokeWidth(dip2px(1.5f)); paint1.setColor(Color.BLACK); paint2.setAntiAlias(true); paint2.setStyle(Paint.Style.FILL); paint2.setColor(Color.BLACK); DisplayMetrics dm = getResources().getDisplayMetrics(); int mScreenWidth = dm.widthPixels; int mScreenHeight = dm.heightPixels; //以分辨率为720*1080准,计算宽高比值 float ratioWidth = (float) mScreenWidth / 720; float ratioHeight = (float) mScreenHeight / 1080; float ratioMetrics = Math.min(ratioWidth, ratioHeight); int textSize = Math.round(20 * ratioMetrics); paint2.setTextSize(textSize); } private int dip2px(float dpValue) { final float scale = getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } @SuppressLint("DrawAllocation") @Override // 重写该方法,进行绘图 protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 大于百分之30时绿色,否则为红色 if (percent > 0.3f) { paint.setColor(Color.GREEN); } else { paint.setColor(Color.RED); } int a = getWidth() - dip2px(2f); int b = getHeight() - dip2px(1.5f); // 根据电量百分比画图 float d = a * percent; float left = dip2px(0.5f); float top = dip2px(0.5f); float right = dip2px(2.5f); float bottom = dip2px(1.5f); RectF re1 = new RectF(left, top, d - right, b + bottom); //电量填充 RectF re2 = new RectF(0, 0, a - right, b + bottom); //电池边框 RectF re3 = new RectF(a - right, b / 5, a, b + bottom - b / 5); //电池正极 // 绘制圆角矩形 canvas.drawRect(re1, paint); canvas.drawRect(re2, paint1); canvas.drawRect(re3, paint2); //文字的起点为(getWidth()/2,getHeight()/2) canvas.drawText(String.valueOf((int) (percent * 100)), getWidth() / 3 - dip2px(3), getHeight() - getHeight() / 4, paint2); } // 每次检测电量都重绘,在检测电量的地方调用 public synchronized void setProgress(int percent) { this.percent = (float) (percent / 100.0); postInvalidate(); }}
图片显示效果:
是截图不大清晰,凑合点看吧
更多相关文章
- [Android(安卓)Traffic] 调整定时更新的频率(C2DM与退避算法)
- 《老罗Android》监听电量变化、Broadcast实现开机启动
- Android之手机电池电量应用
- Android电池架构分析(转)
- Android4.0 battery架构和管理
- android mtk6592 添加led三色灯,红色蓝色绿色
- Android Battery 开发(三) BatteryService
- unity android获取电量和wifi信号强度
- 蓝牙遥控器获取电量GATT