初识Android自定义控件之圆形百分比图表的制作

来源:互联网 发布:商城类网站源码 编辑:程序博客网 时间:2024/05/17 08:50

在做小游戏的时候,会想做一个统计玩家水平百分比的圆形图标,主要有个各个阶段的数据,就可以画出百分比的圆,在了解了安卓简单自定义控件的基础上,利用SharedPreferences进行数据存储,自定义控件完成显示,算法较为简单,初学者应该都能看懂,效果如下:



代码:

自定义控件MyImageView:

public class MyImageView extends ImageView {private Context context;public MyImageView(Context context, AttributeSet attrs) {super(context, attrs);this.context=context;}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);//初始化Paint p=new Paint();//分别是左上右下的顺序参数,这里是一个200×200的正方形RectF r=new RectF(50, 50, 250, 250);p.setColor(Color.BLACK);p.setTextSize(18f);canvas.drawText("水平百分比", 100, 20, p);//用来分别给不同等级的扇形做底色int[] color={R.color.test1,R.color.test2,R.color.test3,R.color.test4,};//访问SharePreferences存储的recordsSharedPreferences sp=context.getSharedPreferences("records", context.MODE_PRIVATE);//默认值设为1,防止第一次没有sum报错,这是作为分母int sum=sp.getInt("sum", 1);//设置旋转角度int range=0;//和初始角度int ori=0;//规范百分比DecimalFormatdf=newDecimalFormat("#");for(int i=0;i<4;i++){p.setColor(getResources().getColor(color[i]));int level=sp.getInt("test"+(i+1), 0);//当前的初始角度是在旋转的角度加上一个数据的初始角度ori=ori+range;range=(level*360)/sum;//计算百分比String percent=df.format((range/360f)*100);//对应颜色显示比例canvas.drawText("test"+i+"目前所占的百分比"+percent+"%", 180, 270+20*i, p);//绘制扇形,起始角度,旋转角度canvas.drawArc(r, ori, range, true, p);}}}
MainActivity:

public class MainActivity extends Activity {        private MyImageView myImageView;           @Override           protected void onCreate(Bundle savedInstanceState) {               super.onCreate(savedInstanceState);               setContentView(R.layout.activity_main);               myImageView=(MyImageView) findViewById(R.id.myImageView);               SharedPreferences.Editor sp=getSharedPreferences("records", MODE_PRIVATE).edit();               sp.putInt("test1", 1);               sp.putInt("test2", 2);               sp.putInt("test3", 4);               sp.putInt("test4", 8);               sp.putInt("sum", 1+2+4+8);               sp.commit();               //刷新              myImageView.postInvalidate();           }}


不足之处:

数据写成传可变参数的,如(int ...)另外sum可以自动从存储的数据中算出来,不需要自己手动写,这样的复用性就更大了。欢迎留言交流

 
0 0