最新公司須要一個電池內帶數字的顯示電池電量需求,百度了一下。參考下面這篇文章寫的Android自定義View之電池電量顯示。java
增長了裏面電池電量數字顯示,還有就是一個屏幕適配。無論屏幕分辨率基本都能適配。直接上代碼吧。android
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(); } }
圖片顯示效果:canvas
是截圖不大清晰,湊合點看吧ide