图表网上有很多第三方工具,但是往往都会受到一些限制,于是用canvas画pieChart.
- Java代码
- // 定义一些常量
- int areaX = 1;
- int areaY = 22;
- int areaWidth;
- int areaHight;
- //pie上的颜色
- int colors[];
- //占的比例
- int percent[];
- int tempAngle = 0;
- private Bitmap bitmap;
- /**
- * 屏幕中间点的X、Y坐标
- */
- private float centerX,centerY;
- /**
- * 大园半径
- */
- private float bigR;
- private Canvas canvas;
- Bitmap OverlayBitmap;
- /**
- * 屏幕的宽
- */
- private int width;
- /**
- * 屏幕的高
- */
- private int height;
- @Override
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
- this.canvas = canvas;
- centerX = width / 2;
- centerY = height / 2;
- bigR = (width - 80) / 2;
- areaWidth = width - 2;
- areaHight = height - 2;
- Paint paint = new Paint();
- paint.setColor(Color.RED);
- paint.setStyle(Style.FILL);
- paint.setAntiAlias(true);
- paint.setStrokeWidth(1);
- canvas.save();
- canvas.rotate(mDegree);
- canvas.translate(centerX, centerY);
- for (int j = 0; j < percent.length; j++) {
- paint.setColor(colors[j]);
- canvas.drawArc(new RectF(-bigR, -bigR,bigR, bigR), tempAngle,percent[j],
- true,paint);tempAngle += percent[j];
- }
- canvas.restore();
- }
把在饼图上占的各个部分,由在初始化此view时传参,代码便灵活使用
- Java代码
- int[] colors =new int[]{Color.rgb(255, 0, 68),Color.rgb(4, 227, 66),Color.rgb(120, 120, 120),Color.rgb(255, 145, 0)};
- int[] percent = new int[]{50,140,100,70};
- PieView pieView = new PieView(this,width,height,colors,percent);
percent 在饼图上所占的比例,无论里面有几个元素,总和都必须是360,不然画出来是有空缺的.
- Java代码
- int mDegree = 0; // 偏移量
- int mPreDegree = 0; // 上次偏移量
- public void calcDegree(boolean bFlag) {
- if (mDegree >= 360) {
- mDegree -= 360;
- }
- if (mDegree < 0) {
- mDegree += 360;
- }
- mPreDegree = mDegree;
- }
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- // TODO Auto-generated method stub
- switch (keyCode) {
- //顺时针转动
- case KeyEvent.KEYCODE_DPAD_LEFT:
- mDegree -= 6;
- calcDegree(false);
- postInvalidate();
- break;
- //逆时针转动
- case KeyEvent.KEYCODE_DPAD_RIGHT:
- mDegree += 6;
- calcDegree(false);
- postInvalidate();
- break;
- default:
- break;
- }
- return super.onKeyDown(keyCode, event);
- }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。