private Context mContext; private float width; private float height; private Paint mPaint; private float powerQuantity=0.5f;//电量
public BatteryState(Context context) {
super(context);
mContext=context;
mPaint = new Paint();
}
public BatteryState(Context context, AttributeSet attrs) {
super(context, attrs);
mContext=context;
mPaint = new Paint();
}
public BatteryState(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext=context;
mPaint = new Paint();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 计算控件尺寸
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onDraw(Canvas canvas) {
//绘制界面
super.onDraw(canvas);
Bitmap batteryBitmap=ReadBitMap(mContext, R.drawable.battery_empty);//读取图片资源
width=batteryBitmap.getWidth();
height=batteryBitmap.getHeight();
if (powerQuantity>0.3f&&powerQuantity<=1) {
// 电量少于30%显示红色
mPaint.setColor(Color.GREEN);
}
else if (powerQuantity>=0&&powerQuantity<=0.3)
{
mPaint.setColor(Color.RED);
}
// 计算绘制电量的区域
float right=width*0.94f;
float left=width*0.21f+(right-width*0.21f)*(1-powerQuantity);
float tope=height*0.45f;
float bottom=height*0.67f;
canvas.drawRect(left,tope,right,bottom,mPaint);
canvas.drawBitmap(batteryBitmap, 0, 0, mPaint);
}
public void refreshPower(float power)
{
powerQuantity=power;
if (powerQuantity>1.0f)
powerQuantity=1.0f;
if (powerQuantity<0)
powerQuantity=0;
invalidate();
}
<LinearLayout
android:layout_width="wrap_content"
android:layout_marginLeft="30dp"
android:layout_height="30dp">
<com.example.administrator.batterytest.BatteryState
android:id="@+id/bs_power"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
mBtnTry = (TextView) findViewById(R.id.btn_try);
mBtnTry.setText("刷新电量");
// mBtnTry.setBackground(getResources().getDrawable(R.drawable.maxwell_sun_5_bar));
mBsPower = (BatteryState) findViewById(R.id.bs_power);
mBtnTry.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
float power = Integer.parseInt(mEtPower.getText().toString());
float p = power / 100;
mBsPower.refreshPower(p);
}
});
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有