希望實現一個折線圖,但沒有找到合適的控制項或者代碼,只有一個基本樣子的,在它的基礎上,進行了一些改進,改得比較靈活,可以傳遞參數,可以設定位置,座標軸長度,刻度長度等。
自訂的ChartView.java
package jetz.common;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class ChartView extends View{
public int XPoint=40; //原點的X座標
public int YPoint=260; //原點的Y座標
public int XScale=55; //X的刻度長度
public int YScale=40; //Y的刻度長度
public int XLength=380; //X軸的長度
public int YLength=240; //Y軸的長度
public String[] XLabel; //X的刻度
public String[] YLabel; //Y的刻度
public String[] Data; //資料
public String Title; //顯示的標題
public ChartView(Context context)
{
super(context);
}
public void SetInfo(String[] XLabels,String[] YLabels,String[] AllData,String strTitle)
{
XLabel=XLabels;
YLabel=YLabels;
Data=AllData;
Title=strTitle;
}
@Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);//重寫onDraw方法
//canvas.drawColor(Color.WHITE);//設定背景顏色
Paint paint= new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setAntiAlias(true);//去鋸齒
paint.setColor(Color.BLUE);//顏色
Paint paint1=new Paint();
paint1.setStyle(Paint.Style.STROKE);
paint1.setAntiAlias(true);//去鋸齒
paint1.setColor(Color.DKGRAY);
paint.setTextSize(12); //設定軸文字大小
//設定Y軸
canvas.drawLine(XPoint, YPoint-YLength, XPoint, YPoint, paint); //軸線
for(int i=0;i*YScale<YLength ;i++)
{
canvas.drawLine(XPoint,YPoint-i*YScale, XPoint+5, YPoint-i*YScale, paint); //刻度
try
{
canvas.drawText(YLabel[i] , XPoint-22, YPoint-i*YScale+5, paint); //文字
}
catch(Exception e)
{
}
}
canvas.drawLine(XPoint,YPoint-YLength,XPoint-3,YPoint-YLength+6,paint); //箭頭
canvas.drawLine(XPoint,YPoint-YLength,XPoint+3,YPoint-YLength+6,paint);
//設定X軸
canvas.drawLine(XPoint,YPoint,XPoint+XLength,YPoint,paint); //軸線
for(int i=0;i*XScale<XLength;i++)
{
canvas.drawLine(XPoint+i*XScale, YPoint, XPoint+i*XScale, YPoint-5, paint); //刻度
try
{
canvas.drawText(XLabel[i] , XPoint+i*XScale-10, YPoint+20, paint); //文字
//資料值
if(i>0&&YCoord(Data[i-1])!=-999&&YCoord(Data[i])!=-999) //保證有效資料
canvas.drawLine(XPoint+(i-1)*XScale, YCoord(Data[i-1]), XPoint+i*XScale, YCoord(Data[i]), paint);
canvas.drawCircle(XPoint+i*XScale,YCoord(Data[i]), 2, paint);
}
catch(Exception e)
{
}
}
canvas.drawLine(XPoint+XLength,YPoint,XPoint+XLength-6,YPoint-3,paint); //箭頭
canvas.drawLine(XPoint+XLength,YPoint,XPoint+XLength-6,YPoint+3,paint);
paint.setTextSize(16);
canvas.drawText(Title, 150, 50, paint);
}
private int YCoord(String y0) //計算繪製時的Y座標,無資料時返回-999
{
int y;
try
{
y=Integer.parseInt(y0);
}
catch(Exception e)
{
return -999; //出錯則返回-999
}
try
{
return YPoint-y*YScale/Integer.parseInt(YLabel[1]);
}
catch(Exception e)
{
}
return y;
}
}
--------------------------------------------------------------------------------------------
調用方法:
ChartView myView=new ChartView(this);
myView.SetInfo(
new String[]{"7-11","7-12","7-13","7-14","7-15","7-16","7-17"}, //X軸刻度
new String[]{"","50","100","150","200","250"}, //Y軸刻度
new int[]{15,23,10,36,45,40,12}, //資料
"表徵圖的標題"
);
效果: