安卓(android)统计图表の曲线图,折线图

package com.yzxy.draw;
 
import java.util.ArrayList;
import java.util.HashMap;
import com.yzxy.draw.tools.Tools;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.Paint.Style;
import android.graphics.Typeface;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
 
/**
*
* @author 云醉晓月
*
*/
@SuppressLint("ViewConstructor")
class MyTuView extends View{
 
public static final int RECT_SIZE = 10;
private Point mSelectedPoint = null;
public static enum Mstyle
{
Line,scroll
}
 
private Mstyle mstyle=Mstyle.Line;
private Point[] mPoints = new Point[8];
 
Context context;
Activity act;
int bheight=0;
Tools tool=new Tools();
HashMap<Double, Double> map;
ArrayList<Double> dlk;
int totalvalue=30;
int pjvalue=5;
String xstr,ystr;
int margint=15;
int marginb=40;
int c=0;
int resid=0;
Boolean isylineshow;
 
/**
* 图表统计曲直线图VIew,为了更高效美观,只支持横向屏幕
* @param context
* @param map 需要的数据,虽然key是double,但是只用于排序和显示,与横向距离无关
* @param totalvalue Y轴的最大值
* @param pjvalue Y平均值
* @param xstr X轴的单位
* @param ystr Y轴的单位
* @param isylineshow 是否显示纵向网格
*/
public MyTuView(Context context,HashMap<Double, Double> map,int totalvalue,int pjvalue,String xstr,String ystr,Boolean isylineshow)
{
super(context);
this.context=context;
this.act = (Activity)context;
this.map=map;
this.totalvalue=totalvalue;
this.pjvalue=pjvalue;
this.xstr=xstr;
this.ystr=ystr;
this.isylineshow=isylineshow;
act.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
 
@SuppressLint("DrawAllocation")
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// canvas.drawColor(Color.GRAY);
if(c!=0)
this.setbg(c);
if(resid!=0)
this.setBackgroundResource(resid);
dlk=tool.getintfrommap(map);
int height=getHeight();
if(bheight==0)
bheight=height-marginb;
 
int width=getWidth();
 
Log.i("w", getWidth()+":"+getHeight());
int blwidh=tool.dip2px(context,50);
int pjsize=totalvalue/pjvalue;
 
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.GRAY);
paint.setStrokeWidth(1);
paint.setStyle(Style.STROKE);
 
// 画直线(横向)
for(int i=0;i<pjsize+1;i++)
{
canvas.drawLine(blwidh,bheight-(bheight/pjsize)*i+margint,width,bheight-(bheight/pjsize)*i+margint, paint);
 
drawline(pjvalue*i+"("+ystr+")", blwidh/2, bheight-(bheight/pjsize)*i+margint, canvas);
}
ArrayList<Integer> xlist=new ArrayList<Integer>();//记录每个x的值
//画直线(纵向)
for(int i=0;i<dlk.size();i++)
{
xlist.add(blwidh+(width-blwidh)/dlk.size()*i);
if(isylineshow)
{
canvas.drawLine(blwidh+(width-blwidh)/dlk.size()*i,margint,blwidh+(width-blwidh)/dlk.size()*i,bheight+margint, paint);
}
drawline(dlk.get(i)+"("+xstr+")", blwidh+(width-blwidh)/dlk.size()*i, bheight+40, canvas);
}
 
Point[] ps=getpoints(dlk, map, xlist, totalvalue, bheight);
mPoints=ps;
 
paint.setColor(Color.BLACK);
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(2);
 
if(mstyle==Mstyle.scroll)
drawscrollline(ps, canvas, paint);
else
drawline(ps, canvas, paint);
 
paint.setColor(Color.RED);
paint.setStyle(Style.FILL);
for (int i=0; i<ps.length; i++)
{
canvas.drawRect(pointToRect(ps[i]),paint);
}
}
 
@Override
public boolean onTouchEvent(MotionEvent event)
{
 
return true;
 
}
 
/**
* 画点
* @param p
* @return
*/
private RectF pointToRect(Point p)
{
return new RectF(p.x -RECT_SIZE/2, p.y - RECT_SIZE/2,p.x + RECT_SIZE/2, p.y + RECT_SIZE/2);
}
 
/**
* 画曲线
* @param startp 开始点
* @param endp 结束点
* @param canvas 画布
* @param paint 画笔
*/
private void drawscrollline(Point[] ps,Canvas canvas,Paint paint)
{
Point startp=new Point();
Point endp=new Point();
for(int i=0;i<ps.length-1;i++)
{
startp=ps[i];
endp=ps[i+1];
int wt=(startp.x+endp.x)/2;
Point p3=new Point();
Point p4=new Point();
p3.y=startp.y;
p3.x=wt;
p4.y=endp.y;
p4.x=wt;
//确定曲线的路径
Path path = new Path();
path.moveTo(startp.x,startp.y);
path.cubicTo(p3.x, p3.y, p4.x, p4.y,endp.x, endp.y);
//绘制
canvas.drawPath(path, paint);
 
}
}
 
/**
* 画直线
* @param ps
* @param canvas
* @param paint
*/
private void drawline(Point[] ps,Canvas canvas,Paint paint)
{
Point startp=new Point();
Point endp=new Point();
for(int i=0;i<ps.length-1;i++)
{
startp=ps[i];
endp=ps[i+1];
canvas.drawLine(startp.x,startp.y,endp.x,endp.y, paint);
}
}
 
/**
* 得到所有点
* @param dlk map的从小到大的索引集合
* @param map 数据
* @param xlist 从左到右点的x轴值集合
* @param max 即totalvalue
* @param h View的高度
* @return 点的数组
*/
private Point[] getpoints(ArrayList<Double> dlk,HashMap<Double, Double> map,ArrayList<Integer> xlist,int max,int h)
{
Point[] points=new Point[dlk.size()];
for(int i=0;i<dlk.size();i++)
{
int ph=h-(int)(h*(map.get(dlk.get(i))/max));
 
points[i]=new Point(xlist.get(i),ph+margint);
}
return points;
}
 
/**
* 写字(天啦,怎么起了这么个名字,歧义)
* @param text 需要写的字
* @param x 字的中心点x值
* @param y 字的中心点y值
* @param canvas 画布
*/
private void drawline(String text,int x,int y,Canvas canvas)
{
Paint p = new Paint();
p.setAlpha(0x0000ff);//蓝色
p.setTextSize(20);
String familyName = "宋体";
Typeface font = Typeface.create(familyName,Typeface.ITALIC);
p.setTypeface(font);
p.setTextAlign(Paint.Align.CENTER);
canvas.drawText(text, x, y, p);
}
public void setbg(int c)
{
this.setBackgroundColor(c);
}
 
public HashMap<Double, Double> getMap() {
return map;
}
 
public void setMap(HashMap<Double, Double> map) {
this.map = map;
}
 
public int getTotalvalue() {
return totalvalue;
}
 
public void setTotalvalue(int totalvalue) {
this.totalvalue = totalvalue;
}
 
public int getPjvalue() {
return pjvalue;
}
 
public void setPjvalue(int pjvalue) {
this.pjvalue = pjvalue;
}
 
public String getXstr() {
return xstr;
}
 
public void setXstr(String xstr) {
this.xstr = xstr;
}
 
public String getYstr() {
return ystr;
}
 
public void setYstr(String ystr) {
this.ystr = ystr;
}
 
public int getMargint() {
return margint;
}
 
public void setMargint(int margint) {
this.margint = margint;
}
 
public Boolean getIsylineshow() {
return isylineshow;
}
 
public void setIsylineshow(Boolean isylineshow) {
this.isylineshow = isylineshow;
}
 
public int getMarginb() {
return marginb;
}
 
public void setMarginb(int marginb) {
this.marginb = marginb;
}
 
public Mstyle getMstyle() {
return mstyle;
}
 
public void setMstyle(Mstyle mstyle) {
this.mstyle = mstyle;
}
 
public int getBheight() {
return bheight;
}
 
public void setBheight(int bheight) {
this.bheight = bheight;
}
 
public int getC() {
return c;
}
 
public void setC(int c) {
this.c = c;
}
 
public int getResid() {
return resid;
}
 
public void setResid(int resid) {
this.resid = resid;
}
 

}



package com.yzxy.draw.tools;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;


public class Tools 
{
private final static String ALBUM_PATH  = Environment.getExternalStorageDirectory() + "/yueqiu/";
/**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public  int dip2px(Context context, float dpValue) 
    {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    
    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public  int px2dip(Context context, float pxValue) 
    {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
    
    
    /**
     * 取的map索引从大到小的集合
     * @param HashMap<Double, Double> map 
     * @return map的从小到大的索引的arraylist
     */
    public ArrayList<Double> getintfrommap(HashMap<Double, Double> map)
    {
    ArrayList<Double> dlk=new ArrayList<Double>();
    int position=0;
    @SuppressWarnings("rawtypes")
Set set= map.entrySet();   
        @SuppressWarnings("rawtypes")
Iterator iterator = set.iterator();
 
while(iterator.hasNext())
{   
@SuppressWarnings("rawtypes")
Map.Entry mapentry  = (Map.Entry)iterator.next();   
dlk.add((Double)mapentry.getKey());

for(int i=0;i<dlk.size();i++)
{
int j=i+1;  
           position=i;  
           Double temp=dlk.get(i);  
           for(;j<dlk.size();j++)
           {  
            if(dlk.get(j)<temp)
            {  
            temp=dlk.get(j);  
            position=j;  
            }  
           }  
           
           dlk.set(position,dlk.get(i)); 
           dlk.set(i,temp);  
}
return dlk;
   
    }


    /**
     * 保存图片
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public Boolean saveFile(Bitmap bm, String fileName) throws IOException {   
    File dirFile = new File(ALBUM_PATH); 
    fileName=fileName.replace("/", "_");
        if(!dirFile.exists())
        {   
            dirFile.mkdir();   
        }   
        File myCaptureFile = new File(ALBUM_PATH + fileName);   
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));   
        Boolean b=bm.compress(Bitmap.CompressFormat.PNG, 80, bos);   
        bos.flush();   
        bos.close();  
        System.out.println("保存成功");
        return b;
    }
}


package com.yzxy.draw;




import java.io.IOException;
import java.util.HashMap;


import com.yzxy.draw.MyTuView.Mstyle;
import com.yzxy.draw.tools.Tools;




import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;


import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Toast;
import android.app.Activity;
import android.content.res.XmlResourceParser;
import android.graphics.Bitmap;
import android.graphics.Color;




public class MainActivity extends Activity {


MyTuView tu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

HashMap<Double, Double> map=new HashMap<Double, Double>();
map.put(1.0, 8.0);
map.put(7.0, 130.0);
map.put(2.0, 4.0);
map.put(3.0, 1.0);
map.put(4.0, 18.0);
map.put(5.0, 160.0);
map.put(6.0, 180.0);
map.put(8.1, 133.5);
tu=new MyTuView(this,map,200,50,"x","y",false);
// tu.setC(Color.CYAN);
tu.setResid(R.drawable.bg);
// tu.setBheight(200);
tu.setTotalvalue(200);

tu.setPjvalue(50);
tu.setXstr("x");
tu.setYstr("y");
tu.setMargint(20);
tu.setBackgroundColor(Color.WHITE);
tu.setMarginb(50);
tu.setMstyle(Mstyle.scroll);
RelativeLayout rela=getlayout(R.layout.activity_main);
rela.addView(tu);
LayoutParams parm=new LayoutParams(1200,400);
parm.setMargins(50, 50, 50, 100);
tu.setLayoutParams(parm);
setContentView(rela);



}

@Override
public boolean onCreateOptionsMenu(Menu menu) 
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}



@Override
public boolean onOptionsItemSelected(MenuItem item) 
{
       // TODO Auto-generated method stub
       if(item.getItemId() == R.id.menu_settings)
       {
        if (false == tu.isDrawingCacheEnabled()) 
    {  
               tu.setDrawingCacheEnabled(true);
           }  
        Bitmap bitmap = tu.getDrawingCache();  
        Tools tool=new Tools();
        try {
Boolean b=tool.saveFile(bitmap, "aaaa.png");
if(b)
Toast.makeText(this, "success", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
       }
       if(item.getItemId() == R.id.menu_ch)
       {
        HashMap<Double, Double> map=new HashMap<Double, Double>();
        map.put(1.0, 21.0);
        map.put(3.0, 25.0);
        map.put(4.0, 32.0);
        map.put(5.0, 31.0);
        map.put(6.0, 26.0);


        tu.setTotalvalue(40);
        tu.setPjvalue(10);
        tu.setMap(map);
        tu.setIsylineshow(true);
        tu.postInvalidate();
       }
       if(item.getItemId() == R.id.menu_ch2)
       {
        HashMap<Double, Double> map=new HashMap<Double, Double>();
        map.put(1.0, 41.0);
        map.put(3.0, 25.0);
        map.put(4.0, 32.0);
        map.put(5.0, 41.0);
        map.put(6.0, 16.0);
        map.put(7.0, 36.0);
        map.put(8.0, 26.0);
        tu.setTotalvalue(50);
        tu.setPjvalue(10);
        tu.setMap(map);
        tu.setMstyle(Mstyle.Line);
        tu.setIsylineshow(false);
        tu.postInvalidate();
       }
       return true;
 }


public RelativeLayout getlayout(int r)
    {
    LayoutInflater inflater = (LayoutInflater)getSystemService(android.content.Context.LAYOUT_INFLATER_SERVICE ); 
  try {
  XmlResourceParser parser = getResources().getLayout(r);
  RelativeLayout layout = (RelativeLayout) inflater.inflate(parser, null);
  return layout;
  }catch (Exception e) {
// TODO: handle exception
}
return null;
}
}

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值