一、背景
最近公司有個業務,需要自定義一個電池控件,是以自己按照UI圖編寫了一個自定義View。
二、效果
三、實作過程
首先看下視覺給出的UI效果圖
從這裡我們可以看得出來,要自定義這個電池View的話,分為3部分來繪制。
- 第一部分是電池頭
- 第二部分是電池邊框
- 第三部分是電池電量
3.1 自定義屬性
是以按照上面的UI效果圖來做的話,我們自定義幾個屬性。
attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--自定義耗電排行電池View的自定義屬性-->
<declare-styleable name="PowerConsumptionRankingsBatteryView">
<!-- 手表低電時候的電池顔色 -->
<attr name="batteryLowerPowerColor" format="color"/>
<!-- 手表線上時候的電池顔色 -->
<attr name="batteryOnlineColor" format="color"/>
<!-- 手表離線時候的電池顔色 -->
<attr name="batteryOfflineColor" format="color"/>
<!-- 電池最大高度 -->
<attr name="batteryLevelMaxHeight" format="integer"/>
<!-- 電池寬度 -->
<attr name="batteryLevelWidth" format="integer"/>
<!-- 外殼的相關資訊 -->
<attr name="batteryShellCornerRadius" format="dimension"/>
<attr name="batteryShellWidth" format="dimension"/>
<attr name="batteryShellHeight" format="dimension"/>
<attr name="batteryShellStrokeWidth" format="dimension"/>
<!-- 電池頭的相關資訊 -->
<attr name="batteryShellHeadCornerRadius" format="dimension"/>
<attr name="batteryShellHeadWidth" format="dimension"/>
<attr name="batteryShellHeadHeight" format="dimension"/>
<!-- 電池外殼和電池等級直接的間距 -->
<attr name="batteryGap" format="dimension"/>
</declare-styleable>
</resources>
執行自定義屬性,包括電池顔色、電池最大高度、電池寬度、電池頭部的相關資訊和電池邊框的相關資訊。
colors.xml 定義了一些UI标注的顔色值
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="lowerPowerColor">#ff4d4d</color>
<color name="onlineColor">#00d68d</color>
<color name="offlineColor">#bfbfbf</color>
</resources>
dimens.xml 定義了一些UI标注的尺寸值
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<!--電池控件 高度-->
<dimen name="power_consumption_rankings_dimen_main_battery_view_height">48dp</dimen>
<!--電池控件 寬度-->
<dimen name="power_consumption_rankings_dimen_main_battery_view_width">31dp</dimen>
<!--電池外殼 厚度-->
<dimen name="power_consumption_rankings_dimen_main_battery_view_shell_stroke_width">2.5dp
</dimen>
<!--電池外殼 寬度-->
<dimen name="power_consumption_rankings_dimen_main_battery_view_shell_width">28dp</dimen>
<!--電池外殼 高度-->
<dimen name="power_consumption_rankings_dimen_main_battery_view_shell_height">42dp</dimen>
<!--電池外殼 圓角-->
<dimen name="power_consumption_rankings_dimen_main_battery_view_shell_corner">3dp</dimen>
<!--電池頭 寬度-->
<dimen name="power_consumption_rankings_dimen_main_battery_view_head_width">14dp</dimen>
<!--電池頭 高度-->
<dimen name="power_consumption_rankings_dimen_main_battery_view_head_height">3dp</dimen>
<!--電池頭 圓角-->
<dimen name="power_consumption_rankings_dimen_main_battery_view_head_corner">2dp</dimen>
<!--電池外殼和電池等級直接的間距-->
<dimen name="power_consumption_rankings_dimen_main_battery_view_gap">2dp</dimen>
<!--電池 寬度-->
<dimen name="power_consumption_rankings_dimen_main_battery_level_width">22dp</dimen>
<!--電池 最大高度-->
<dimen name="power_consumption_rankings_dimen_main_battery_level_max_height">35dp</dimen>
</resources>
3.2 實作自定義View
建立PowerConsumptionRankingsBatteryView繼承View,
在View的構造方法中,擷取我們需要的自定義樣式,重寫onMesure,onDraw方法。
package com.oyp.battery;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.DrawFilter;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
/**
* 自定義 耗電排行内的 電池圖示
* </p>
* created by OuyangPeng at 2018/6/10 下午 05:57
*
* @author OuyangPeng
*/
public class PowerConsumptionRankingsBatteryView extends View {
/**
* 電池最大電量
*/
public static final int MAX_LEVEL = 100;
/**
* 電池預設電量
*/
public static final int DEFAULT_LEVEL = 40;
/**
* 自定義View的寬
*/
private int width;
/**
* 自定義View的高
*/
private int height;
/**
* 抗鋸齒标志
*/
private DrawFilter drawFilter;
/**
* 電池外殼 厚度
*/
private int shellStrokeWidth;
/**
* 電池外殼 圓角
*/
private int shellCornerRadius;
/**
* 電池外殼 寬度
*/
private int shellWidth;
/**
* 電池外殼 寬度
*/
private int shellHeight;
/**
* 電池頭 圓角
*/
private int shellHeadCornerRadius;
/**
* 電池頭 寬度
*/
private int shellHeadWidth;
/**
* 電池頭 高度
*/
private int shellHeadHeight;
/**
* 電池寬度
*/
private int levelWidth;
/**
* 電池最大高度
*/
private int levelMaxHeight;
/**
* 電池高度
*/
private int levelHeight = 100;
/**
* 電池外殼和電池等級直接的間距
*/
private int gap;
/**
* 電池外殼 畫筆
*/
private Paint shellPaint;
/**
* 電池外殼
*/
private RectF shellRectF;
/**
* 電池頭
*/
private RectF shellHeadRect;
/**
* 電池電量 畫筆
*/
private Paint levelPaint;
/**
* 電池電量
*/
private RectF levelRect;
/**
* 低電顔色
*/
private int lowerPowerColor;
/**
* 線上顔色
*/
private int onlineColor;
/**
* 離線顔色
*/
private int offlineColor;
public PowerConsumptionRankingsBatteryView(Context context) {
super(context);
}
public PowerConsumptionRankingsBatteryView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
drawFilter = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
initTypeArray(context, attrs);
//設定 電池殼畫筆的相關屬性
shellPaint = new Paint();
shellPaint.setAntiAlias(true);
shellPaint.setColor(onlineColor);
shellPaint.setStrokeWidth(shellStrokeWidth);
shellPaint.setAntiAlias(true);
//設定 電池畫筆的相關屬性
levelPaint = new Paint();
levelPaint.setColor(onlineColor);
levelPaint.setStyle(Paint.Style.FILL);
levelPaint.setStrokeWidth(levelWidth);
shellRectF = new RectF();
shellHeadRect = new RectF();
levelRect = new RectF();
}
/**
* 初始化自定義屬性
*/
private void initTypeArray(Context context, @Nullable AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.PowerConsumptionRankingsBatteryView);
lowerPowerColor = typedArray.getColor(R.styleable.PowerConsumptionRankingsBatteryView_batteryLowerPowerColor,
getResources().getColor(R.color.lowerPowerColor));
onlineColor = typedArray.getColor(R.styleable.PowerConsumptionRankingsBatteryView_batteryOnlineColor,
getResources().getColor(R.color.onlineColor));
offlineColor = typedArray.getColor(R.styleable.PowerConsumptionRankingsBatteryView_batteryOfflineColor,
getResources().getColor(R.color.offlineColor));
//外殼的相關資訊
shellCornerRadius = typedArray.getDimensionPixelOffset(R.styleable.PowerConsumptionRankingsBatteryView_batteryShellCornerRadius,
getResources().getDimensionPixelOffset(R.dimen.power_consumption_rankings_dimen_main_battery_view_shell_corner));
shellWidth = typedArray.getDimensionPixelOffset(R.styleable.PowerConsumptionRankingsBatteryView_batteryShellWidth,
getResources().getDimensionPixelOffset(R.dimen.power_consumption_rankings_dimen_main_battery_view_shell_width));
shellHeight = typedArray.getDimensionPixelOffset(R.styleable.PowerConsumptionRankingsBatteryView_batteryShellHeight,
getResources().getDimensionPixelOffset(R.dimen.power_consumption_rankings_dimen_main_battery_view_shell_height));
shellStrokeWidth = typedArray.getDimensionPixelOffset(R.styleable.PowerConsumptionRankingsBatteryView_batteryShellStrokeWidth,
getResources().getDimensionPixelOffset(R.dimen.power_consumption_rankings_dimen_main_battery_view_shell_stroke_width));
//電池頭的相關資訊
shellHeadCornerRadius = typedArray.getDimensionPixelOffset(R.styleable.PowerConsumptionRankingsBatteryView_batteryShellHeadCornerRadius,
getResources().getDimensionPixelOffset(R.dimen.power_consumption_rankings_dimen_main_battery_view_head_corner));
shellHeadWidth = typedArray.getDimensionPixelOffset(R.styleable.PowerConsumptionRankingsBatteryView_batteryShellHeadWidth,
getResources().getDimensionPixelOffset(R.dimen.power_consumption_rankings_dimen_main_battery_view_head_width));
shellHeadHeight = typedArray.getDimensionPixelOffset(R.styleable.PowerConsumptionRankingsBatteryView_batteryShellHeadHeight,
getResources().getDimensionPixelOffset(R.dimen.power_consumption_rankings_dimen_main_battery_view_head_height));
//電池最大高度
levelMaxHeight = typedArray.getDimensionPixelOffset(R.styleable.PowerConsumptionRankingsBatteryView_batteryLevelMaxHeight,
getResources().getDimensionPixelOffset(R.dimen.power_consumption_rankings_dimen_main_battery_level_max_height));
//電池寬度
levelWidth = typedArray.getDimensionPixelOffset(R.styleable.PowerConsumptionRankingsBatteryView_batteryLevelWidth,
getResources().getDimensionPixelOffset(R.dimen.power_consumption_rankings_dimen_main_battery_level_width));
//電池外殼和電池等級直接的間距
gap = typedArray.getDimensionPixelOffset(R.styleable.PowerConsumptionRankingsBatteryView_batteryGap,
getResources().getDimensionPixelOffset(R.dimen.power_consumption_rankings_dimen_main_battery_view_gap));
//回收typedArray
typedArray.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//對View上的內容進行測量後得到的View內容占據的寬度
width = getMeasuredWidth();
//對View上的內容進行測量後得到的View內容占據的高度
height = getMeasuredHeight();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.setDrawFilter(drawFilter);
// 電池頭 矩形的坐标
//坐标 left:控件整體寬度的一半 減去 電池頭寬度的一半
shellHeadRect.left = width / 2 - shellHeadWidth / 2;
//坐标 top: 0
shellHeadRect.top = 0;
//坐标 right:控件整體寬度的一半 加上 電池頭寬度的一半
shellHeadRect.right = width / 2 + shellHeadWidth / 2;
//坐标 bottom:電池頭的高度
shellHeadRect.bottom = shellHeadHeight;
// 電池殼 矩形的坐标
//坐标 left:電池殼厚度的一半
shellRectF.left = shellStrokeWidth / 2;
//坐标 left:電池殼厚度的一半 加上 電池頭的高度
shellRectF.top = shellStrokeWidth / 2 + shellHeadHeight;
//坐标 right:控件整體寬度 減去 電池殼厚度的一半
shellRectF.right = width - shellStrokeWidth / 2;
//坐标 bottom:控件整體高度 減去 電池殼厚度的一半
shellRectF.bottom = height - shellStrokeWidth / 2;
// 電池電量 矩形的坐标
//坐标 left:電池殼厚度的一半 加上 電池外殼和電池等級直接的間距
levelRect.left = shellStrokeWidth + gap;
//電池滿格時候的最大高度 :(控件整體高度 減去電池殼厚度 減去電池頭高度 減去 電池外殼和電池等級直接的間距的兩倍)
//topOffset: 電池滿格時候的最大高度 * (電池滿格100 - 目前的電量)/ 電池滿格100
float topOffset = (height - shellHeadHeight - gap * 2 - shellStrokeWidth) * (MAX_LEVEL - levelHeight) / MAX_LEVEL;
//坐标 top:電池頭的高度 + 電池殼的厚度 + 電池外殼和電池等級直接的間距 + topOffset
levelRect.top = shellHeadHeight + shellStrokeWidth + gap + topOffset;
//坐标 right:控件整體寬度 減去 電池殼厚度的一半 減去 電池外殼和電池等級直接的間距
levelRect.right = width - shellStrokeWidth - gap;
//坐标 bottom:控件整體寬度 減去 電池殼厚度的一半 減去 電池外殼和電池等級直接的間距
levelRect.bottom = height - shellStrokeWidth - gap;
//繪制電池頭
shellPaint.setStyle(Paint.Style.FILL);
canvas.drawRoundRect(shellHeadRect, shellHeadCornerRadius, shellHeadCornerRadius, shellPaint);
//由于電池頭的左下角和右下角不是圓角的,是以我們需要畫一個矩形 覆寫圓角
//繪制左下角矩形
canvas.drawRect(shellHeadRect.left, shellHeadRect.bottom - shellHeadCornerRadius,
shellHeadRect.left + shellHeadCornerRadius, shellHeadRect.bottom, shellPaint);
//繪制右下角矩形
canvas.drawRect(shellHeadRect.right - shellHeadCornerRadius, shellHeadRect.bottom - shellHeadCornerRadius,
shellHeadRect.right, shellHeadRect.bottom, shellPaint);
//繪制電池殼
shellPaint.setStyle(Paint.Style.STROKE);
canvas.drawRoundRect(shellRectF, shellCornerRadius, shellCornerRadius, shellPaint);
//繪制電池等級
canvas.drawRect(levelRect, levelPaint);
}
/**
* 設定電池電量
*
* @param level
*/
public void setLevelHeight(int level) {
this.levelHeight = level;
if (this.levelHeight < 0) {
levelHeight = MAX_LEVEL;
} else if (this.levelHeight > MAX_LEVEL) {
levelHeight = MAX_LEVEL;
}
postInvalidate();
}
/**
* 設定線上 重繪
*/
public void setOnline() {
shellPaint.setColor(onlineColor);
levelPaint.setColor(onlineColor);
postInvalidate();
}
/**
* 設定離線 重繪
*/
public void setOffline() {
shellPaint.setColor(offlineColor);
levelPaint.setColor(offlineColor);
postInvalidate();
}
/**
* 設定低電 重繪
*/
public void setLowerPower() {
shellPaint.setColor(lowerPowerColor);
levelPaint.setColor(lowerPowerColor);
postInvalidate();
}
}
3.3 使用我們的自定義View
activity_main.xml 中使用我們的自定義View
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/constraintLayout"
tools:context=".MainActivity">
<com.oyp.battery.PowerConsumptionRankingsBatteryView
android:id="@+id/mPowerConsumptionRankingsBatteryView"
android:layout_width="@dimen/power_consumption_rankings_dimen_main_battery_view_width"
android:layout_height="@dimen/power_consumption_rankings_dimen_main_battery_view_height"
android:layout_marginTop="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/tv1"
android:layout_width="match_parent"
android:layout_height="86dp"
android:text="@string/ouyangpeng"
android:gravity="center_horizontal"
app:layout_constraintEnd_toEndOf="@id/constraintLayout"
app:layout_constraintStart_toStartOf="@id/constraintLayout"
app:layout_constraintTop_toTopOf="@+id/constraintLayout"
app:layout_constraintBottom_toBottomOf="@+id/constraintLayout"
/>
</android.support.constraint.ConstraintLayout>
3.4 動态展示不同狀态下的電池View
MainActivity.java 檔案中 動态更新電池的狀态
package com.oyp.battery;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;
/**
* 自定義View 展示界面
* </p>
* created by OuyangPeng at 2018/6/15 下午 03:33
* @author OuyangPeng
*/
public class MainActivity extends AppCompatActivity implements BaseHandlerCallBack {
private PowerConsumptionRankingsBatteryView mPowerConsumptionRankingsBatteryView;
private int power;
private NoLeakHandler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new NoLeakHandler(this);
mPowerConsumptionRankingsBatteryView = (PowerConsumptionRankingsBatteryView) findViewById(R.id.mPowerConsumptionRankingsBatteryView);
new Timer().schedule(new TimerTask() {
@Override
public void run() {
mHandler.sendEmptyMessage(0);
}
}, 0, 100);
}
@Override
protected void onDestroy() {
super.onDestroy();
mHandler.removeCallbacksAndMessages(null);
}
@Override
public void callBack(Message msg) {
switch (msg.what) {
case 0:
mPowerConsumptionRankingsBatteryView.setLevelHeight(power += 5);
if (power == 100) {
power = 0;
}
if (power < 30) {
mPowerConsumptionRankingsBatteryView.setLowerPower();
} else if (power < 60) {
mPowerConsumptionRankingsBatteryView.setOffline();
} else {
mPowerConsumptionRankingsBatteryView.setOnline();
}
break;
default:
break;
}
}
private static class NoLeakHandler<T extends BaseHandlerCallBack> extends Handler {
private WeakReference<T> wr;
public NoLeakHandler(T t) {
wr = new WeakReference<>(t);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
T t = wr.get();
if (t != null) {
t.callBack(msg);
}
}
}
}
BaseHandlerCallBack 定義的接口
package com.oyp.battery;
import android.os.Message;
public interface BaseHandlerCallBack {
public void callBack(Message msg);
}
3.5 效果
四、github源代碼
https://github.com/ouyangpeng/PowerConsumptionRankingsBatteryView作者:歐陽鵬 歡迎轉載,與人分享是進步的源泉!
轉載請保留原文位址:
https://blog.csdn.net/ouyang_peng/article/details/80372805