继续常规图的绘制研究,在这绘制了个环形图(Dount Chart),很简单,大圆套小圆就出来了。呵呵,照例先上猛照:
怎么样,效果还可以吧,实现代码很少,附上:
package com.xcl.chart; /** * Canvas练习 * 自已画环形图(Dount Chart) * * author:xiongchuanliang * date:2014-4-12 */ import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.util.DisplayMetrics; import android.view.View; public class PanelDountChart2 extends View{ private int ScrWidth,ScrHeight; //演示用的百分比例,实际使用中,即为外部传入的比例参数 private final float arrPer[] = new float[]{20f,30f,10f,40f}; //RGB颜色数组 private final int arrColorRgb[][] = { {77, 83, 97}, {148, 159, 181}, {253, 180, 90}, {52, 194, 188}} ; public PanelDountChart2(Context context) { super(context); // TODO Auto-generated constructor stub //屏幕信息 DisplayMetrics dm = getResources().getDisplayMetrics(); ScrHeight = dm.heightPixels; ScrWidth = dm.widthPixels; } public void onDraw(Canvas canvas){ //画布背景 canvas.drawColor(Color.WHITE); float cirX = ScrWidth / 2; float cirY = ScrHeight / 3 ; float radius = ScrHeight / 5 ;//150; float arcLeft = cirX - radius; float arcTop = cirY - radius ; float arcRight = cirX + radius ; float arcBottom = cirY + radius ; RectF arcRF0 = new RectF(arcLeft ,arcTop,arcRight,arcBottom); //画笔初始化 Paint PaintArc = new Paint(); PaintArc.setAntiAlias(true); Paint PaintLabel = new Paint(); PaintLabel.setTextSize(22); canvas.drawText("author:xiongchuanliang", 50, ScrHeight - 280, PaintLabel); PaintLabel.setColor(Color.WHITE); PaintLabel.setTextSize(16); //位置计算类 XChartCalc xcalc = new XChartCalc(); float Percentage = 0.0f; float CurrPer = 0.0f; int i= 0; for(i=0; i<arrPer.length; i++) { //将百分比转换为饼图显示角度 Percentage = 360 * (arrPer[i]/ 100); Percentage = (float)(Math.round(Percentage *100))/100; //分配颜色 PaintArc.setARGB(255,arrColorRgb[i][0], arrColorRgb[i][1], arrColorRgb[i][2]); //在饼图中显示所占比例 canvas.drawArc(arcRF0, CurrPer, Percentage, true, PaintArc); //计算百分比标签 xcalc.CalcArcEndPointXY(cirX, cirY, radius - radius/2/2, CurrPer + Percentage/2); //标识 canvas.drawText(Float.toString(arrPer[i])+"%",xcalc.getPosX(), xcalc.getPosY() ,PaintLabel); //下次的起始角度 CurrPer += Percentage; } //画圆心 PaintArc.setColor(Color.WHITE); canvas.drawCircle(cirX,cirY,radius/2,PaintArc); } }
就这很么点代码就搞定了。 所以说简单的图完全可以不用图表库的。
代码中用到的类,在我前面的例子中找即可。
Android Canvas练习(1)画一张报表来玩
Android Canvas练习(2)自已绘饼图
Android Canvas练习(3)自已绘柱形图
Android Canvas练习(4)自已绘折线图
Android Canvas练习(5)自已绘面积图(Area Chart)
MAIL: [email protected]
BLOG: http://blog.csdn.net/xcl168