Android自定义View之电池电量显示
2016-03-03 14:32
387 查看
自定义简单的电池电量显示。话不多说,直接上代码
在layout布局中调用后,显示效果为
欢迎指点,不喜勿喷
package com.kimascend.thermometer.customview; 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.view.View; public class DrawView extends View { private float percent = 1.0f; public DrawView(Context context, AttributeSet set) { super(context, set); } @Override // 重写该方法,进行绘图 protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 电池电量外面的大白框 Paint paint = new Paint(); // 电池电量里面的绿色 Paint paint1 = new Paint(); // 电池头部 Paint paint2 = new Paint(); // 去锯齿 paint.setAntiAlias(true); paint.setStyle(Paint.Style.FILL); // 大于百分之30时绿色,否则为红色 if (percent > 0.3f) { paint.setColor(Color.GREEN); } else { paint.setColor(Color.RED); } paint1.setAntiAlias(true); paint1.setStyle(Paint.Style.STROKE); paint1.setStrokeWidth(4); paint1.setColor(Color.WHITE); paint2.setAntiAlias(true); paint2.setStyle(Paint.Style.FILL); paint2.setColor(Color.WHITE); int a = getWidth() - 4; int b = getHeight() - 4; // 根据电量百分比画图 float d = a * percent; RectF re1 = new RectF(4, 4, d - 10, b); RectF re2 = new RectF(0, 0, a - 6, b + 4); RectF re3 = new RectF(a - 8, b / 2 - 8, a, b - 6); // 绘制圆角矩形 canvas.drawRect(re1, paint); canvas.drawRect(re2, paint1); canvas.drawRect(re3, paint2); } // 每次检测电量都重绘,在检测电量的地方调用 public synchronized void setProgress(int percent) { this.percent = (float) (percent / 100.0); postInvalidate(); } }
在layout布局中调用后,显示效果为
欢迎指点,不喜勿喷
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories