Android自定义控件实现折线图

本文实例实现一个如下图所示的Android折线图,供大家参考,具体内容如下

首先是控件绘图区域的划分,控件左边取一小部分(控件总宽度的八分之一)绘制表头,右边剩余的部分绘制表格

确定表格的行列数,首先绘制一个三行八列的网格,设置好行列的坐标后开始绘制

/*绘制三条横线*/
for(int i=0;i<3;i++){
  canvas.drawLine(textWide, mLineYs[i], totalWidth, mLineYs[i], mPaintLine);
}
/*绘制八条竖线*/
for(int i=0;i<8;i++){
  canvas.drawLine(mLineXs[i], 0, mLineXs[i], totalHeight, mPaintLine);
}

网格绘制完成后,开始绘制折线图

根据输入的节点数据,分别绘制两条折线

通过canvas的drawLine方法依次连接两点即可

在每个数据节点处绘制一个小圆,突出显示

/*绘制第一条折线的路径*/
for (int i = 0; i < mPerformance_1.length - 1; i++) {
  /*折线图的折线的画笔设置粗一点*/
  mPaintLine.setStrokeWidth(5);
  /*计算当前节点的坐标值*/
  float prePointX =mLineXs[i];
  float prePointY =mLineYs[2] - (mLineYs[2] - mLineYs[mPerformance_1[i].type]) * animCurrentValue;
  /*计算下一个节点的坐标值*/
  float nextPointX=mLineXs[i + 1];
  float nextPointY=mLineYs[2] - (mLineYs[2] - mLineYs[mPerformance_1[i + 1].type]) * animCurrentValue;
  /*连接当前坐标和下一个坐标,绘制线段*/
  canvas.drawLine(prePointX, prePointY, nextPointX, nextPointY, mPaintLine1);
  /*当前节点坐标处绘制小圆*/
  canvas.drawCircle(prePointX, prePointY, mSmallDotRadius, mPointPaint);
}

两条折线重合的地方,需要特殊考虑,比如希望两条折线重合的地方折线变为白色

设置下两条折线的画笔即可

mPaintLine2.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SCREEN));
mPaintLine1.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SCREEN));

测试代码及效果;

final Random random=new Random();
final LineChartView myView=(LineChartView)findViewById(R.id.custom_view);
final LineChartView.Performance[] performances1=new LineChartView.Performance[8];
final LineChartView.Performance[] performances2=new LineChartView.Performance[8];
myView.setOnClickListener(new View.OnClickListener(){
  @Override
  public void onClick(View v){
    for(int i=0;i<performances1.length;i++){
      switch (random.nextInt(2016)%3){
        case 0:
          performances1[i]= LineChartView.Performance.WIN;
          break;
        case 1:
          performances1[i]= LineChartView.Performance.DRAW;
          break;
        case 2:
          performances1[i]= LineChartView.Performance.LOSE;
          break;
        default:
          performances1[i]= LineChartView.Performance.LOSE;
          break;
      }
      switch (random.nextInt(2016)%3){
        case 0:
          performances2[i]= LineChartView.Performance.WIN;
          break;
        case 1:
          performances2[i]= LineChartView.Performance.DRAW;
          break;
        case 2:
          performances2[i]= LineChartView.Performance.LOSE;
          break;
        default:
          performances1[i]= LineChartView.Performance.LOSE;
          break;
      }
    }
    myView.setPerformances(performances1,performances2);
  }
});

完整代码如下:

public class LineChartView extends View {
  private Context context;
  /*动画插值器*/
  DecelerateInterpolator mDecelerateInterpolator = new DecelerateInterpolator();
  /*动画刷新的次数*/
  private int mDuration = 10;
  /*当前动画进度值*/
  private int mCurrentTime = 0;
  private Performance[] mPerformance_1, mPerformance_2;
  /*两条折线的颜色*/
  private int mLineColor1, mLineColor2;
  /*绘制表头文字画笔*/
  private Paint mPaintText = new Paint();
  /*绘制表格的画笔*/
  private Paint mPaintLine = new Paint();
  /*第一条折线的画笔*/
  private Paint mPaintLine1 =new Paint();
  /*第二条折线的画笔*/
  private Paint mPaintLine2 =new Paint();
  /*坐标点的小圆点画笔*/
  private Paint mPointPaint = new Paint();
  private float mSmallDotRadius = 4;
  private TypedValue typedValue;
  private int mPaintClolor;
  /*Handler刷新界面产生动画效果*/
  private Handler mHandler = new Handler();
  private Runnable mAnimation = new Runnable() {
    @Override
    public void run() {
      if (mCurrentTime < mDuration) {
        mCurrentTime++;
        LineChartView.this.invalidate();
      }
    }
  };

  public LineChartView(Context context) {
    super(context);
    this.context=context;
    init();
  }

  public LineChartView(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.context=context;
    init();
  }

  public LineChartView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    this.context=context;
    init();
  }

  public enum Performance {
    WIN(0),
    DRAW(1),
    LOSE(2);
    public int type;
    Performance(int type) {
      this.type = type;
    }
  }

  public void setPerformances(Performance[] performance1, Performance[] performance2) {
    if (performance1 == null) {
      performance1 = new Performance[0];
    }
    if (performance2 == null) {
      performance2 = new Performance[0];
    }
    mPerformance_1 = Arrays.copyOf(performance1, performance1.length > 8 ? 8 : performance1.length);
    mPerformance_2 = Arrays.copyOf(performance2, performance2.length > 8 ? 8 : performance2.length);
    if (isShown()) {
      mCurrentTime = 0;
      this.invalidate();
    }
  }

  /**
   * 设置折线1的颜色
   *
   * @param mLineColor1
   */
  public void setLineColor1(int mLineColor1) {
    this.mLineColor1 = mLineColor1;
  }

  /**
   * 设置折线2的颜色
   *
   * @param mLineColor2
   */
  public void setLineColor2(int mLineColor2) {
    this.mLineColor2 = mLineColor2;
  }

  private void init() {
    mLineColor1=Color.BLUE;
    mLineColor2 = Color.GREEN;
    typedValue=new TypedValue();
    context.getTheme().resolveAttribute(R.attr.title_bar,typedValue,true);
    mPaintClolor =getResources().getColor(typedValue.resourceId);

    final LineChartView.Performance[] performances1=new LineChartView.Performance[8];
    final LineChartView.Performance[] performances2=new LineChartView.Performance[8];
    final Random random=new Random();
    for(int i=0;i<performances1.length;i++){
      switch (random.nextInt(2016)%3){
        case 0:
          performances1[i]= LineChartView.Performance.WIN;
          break;
        case 1:
          performances1[i]= LineChartView.Performance.DRAW;
          break;
        case 2:
          performances1[i]= LineChartView.Performance.LOSE;
          break;
        default:
          performances1[i]= LineChartView.Performance.LOSE;
          break;
      }
      switch (random.nextInt(2016)%3){
        case 0:
          performances2[i]= LineChartView.Performance.WIN;
          break;
        case 1:
          performances2[i]= LineChartView.Performance.DRAW;
          break;
        case 2:
          performances2[i]= LineChartView.Performance.LOSE;
          break;
        default:
          performances1[i]= LineChartView.Performance.LOSE;
          break;
      }
    }
    setPerformances(performances1,performances2);
  }

  /**
   * @param canvas
   */
  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    /*获取控件总宽高*/
    float totalWidth = getWidth();
    float totalHeight = getHeight();
    /*左边取总宽度的八分之一绘制表格头部*/
    float textWide = totalWidth / 8;
    /*左边留一点空白*/
    float left_offset = 10;
    /*折线图的总宽度等于控件的总宽度减去表头和留白*/
    float chartWide = totalWidth - textWide - left_offset;
    /*一共三行,设置每一行的垂直坐标*/
    float[] mLineYs = new float[]{totalHeight / 8, totalHeight / 2, totalHeight * 7 / 8};
    /*一共八列,设置每一列的水平坐标*/
    float[] mLineXs = new float[]{
        textWide + left_offset + chartWide * 0 / 8,
        textWide + left_offset + chartWide * 1 / 8,
        textWide + left_offset + chartWide * 2 / 8,
        textWide + left_offset + chartWide * 3 / 8,
        textWide + left_offset + chartWide * 4 / 8,
        textWide + left_offset + chartWide * 5 / 8,
        textWide + left_offset + chartWide * 6 / 8,
        textWide + left_offset + chartWide * 7 / 8,
    };

    /*绘制表头文字*/
    mPaintText.setStyle(Paint.Style.FILL);
    mPaintText.setColor(mPaintClolor);
    mPaintText.setAlpha(226);
    mPaintText.setTextSize(28);
    /*从中间开始绘制*/
    mPaintText.setTextAlign(Paint.Align.CENTER);
    /*测量文字大小,并计算偏移量*/
    Paint.FontMetrics fontMetrics = mPaintText.getFontMetrics();
    float textBaseLineOffset = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom;
    canvas.drawText("胜场", textWide / 2, mLineYs[0] + textBaseLineOffset, mPaintText);
    canvas.drawText("平局", textWide / 2, mLineYs[1] + textBaseLineOffset, mPaintText);
    canvas.drawText("负场", textWide / 2, mLineYs[2] + textBaseLineOffset, mPaintText);

    /*绘制表格画笔设置*/
    mPaintLine.setStyle(Paint.Style.STROKE);
    mPaintLine.setAntiAlias(true);
    mPaintLine.setColor(mPaintClolor);
    mPaintLine.setAlpha(80);
    mPaintLine.setStrokeWidth(1);
    /*开始绘制表格*/
    /*绘制三条横线*/
    for(int i=0;i<3;i++){
      canvas.drawLine(textWide, mLineYs[i], totalWidth, mLineYs[i], mPaintLine);
    }
    /*绘制八条竖线*/
    for(int i=0;i<8;i++){
      canvas.drawLine(mLineXs[i], 0, mLineXs[i], totalHeight, mPaintLine);
    }
    /*折线图画笔设置*/
    mPaintLine1.setStyle(Paint.Style.STROKE);
    /*设置透明度,取值范围为0~255,数值越小越透明,0表示完全透明*/
    mPaintLine1.setAlpha(0);
    mPaintLine1.setAntiAlias(true);
    mPaintLine1.setColor(mLineColor1);
    mPaintLine1.setStrokeWidth(5);
    mPaintLine2.setStyle(Paint.Style.STROKE);
    /*设置透明度,取值范围为0~255,数值越小越透明,0表示完全透明*/
    mPaintLine2.setAlpha(0);
    mPaintLine2.setAntiAlias(true);
    mPaintLine2.setColor(mLineColor2);
    mPaintLine2.setStrokeWidth(5);
    if (typedValue.resourceId==R.color.white){
      /*PorterDuff.Mode.SCREEN 上下层都显示。*/
      mPaintLine2.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SCREEN));
      mPaintLine1.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SCREEN));
    }else {
      /*PorterDuff.Mode.DARKEN 上下层都显示。变暗*/
      mPaintLine2.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DARKEN));
      mPaintLine1.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DARKEN));
    }
    /*画节点处的小圆点的画笔设置*/
    mPointPaint.setStyle(Paint.Style.STROKE);
    mPointPaint.setAntiAlias(true);
    mPointPaint.setColor(mPaintClolor);

    /*计算当前动画进度对应的数值*/
    float animCurrentValue = mDecelerateInterpolator.getInterpolation(1.0f * mCurrentTime / mDuration);
    mPaintLine.setColor(mLineColor1);
    /*绘制第一条折线的路径*/
    for (int i = 0; i < mPerformance_1.length - 1; i++) {
      /*折线图的折线的画笔设置粗一点*/
      mPaintLine.setStrokeWidth(5);
      /*计算当前节点的坐标值*/
      float prePointX =mLineXs[i];
      float prePointY =mLineYs[2] - (mLineYs[2] - mLineYs[mPerformance_1[i].type]) * animCurrentValue;
      /*计算下一个节点的坐标值*/
      float nextPointX=mLineXs[i + 1];
      float nextPointY=mLineYs[2] - (mLineYs[2] - mLineYs[mPerformance_1[i + 1].type]) * animCurrentValue;
      /*连接当前坐标和下一个坐标,绘制线段*/
      canvas.drawLine(prePointX, prePointY, nextPointX, nextPointY, mPaintLine1);
      /*当前节点坐标处绘制小圆*/
      canvas.drawCircle(prePointX, prePointY, mSmallDotRadius, mPointPaint);
    }
    /*第一个折线图的最后一个节点的坐标*/
    float lastPointX=mLineXs[mPerformance_1.length - 1];
    float lastPointY= mLineYs[2] - (mLineYs[2] - mLineYs[mPerformance_1[mPerformance_1.length - 1].type]) * animCurrentValue;
    /*绘制最后一个节点的外围小圆*/
    canvas.drawCircle(lastPointX,lastPointY ,mSmallDotRadius, mPointPaint);

    /*绘制第二条折线*/
    mPaintLine.setColor(mLineColor2);
    for (int i = 0; i < mPerformance_2.length - 1; i++) {
      /*折线图的折线的画笔设置粗一点*/
      mPaintLine.setStrokeWidth(5);
      /*计算当前节点的坐标值*/
      float prePointX =mLineXs[i];
      float prePointY =mLineYs[2] - (mLineYs[2] - mLineYs[mPerformance_2[i].type]) * animCurrentValue;
      /*计算下一个节点的坐标值*/
      float nextPointX=mLineXs[i + 1];
      float nextPointY=mLineYs[2] - (mLineYs[2] - mLineYs[mPerformance_2[i + 1].type]) * animCurrentValue;
      /*连接当前坐标和下一个坐标,绘制线段*/
      canvas.drawLine(prePointX, prePointY, nextPointX, nextPointY, mPaintLine2);
      /*当前节点坐标处绘制小圆*/
      canvas.drawCircle(prePointX, prePointY, mSmallDotRadius, mPointPaint);
    }
     /*第一个折线图的最后一个节点的坐标*/
    lastPointX=mLineXs[mPerformance_2.length - 1];
    lastPointY= mLineYs[2] - (mLineYs[2] - mLineYs[mPerformance_2[mPerformance_2.length - 1].type]) * animCurrentValue;
    /*绘制最后一个节点的外围小圆*/
    canvas.drawCircle(lastPointX,lastPointY ,mSmallDotRadius, mPointPaint);
    mHandler.postDelayed(mAnimation, 20);
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Android自定义可左右滑动和点击的折线图

    前言 前几天有小盆友让我写一个折线图,可以点击,可以左右滑动.对于折线肯定有很多项目都使用过,所以网上肯定也有很多demo,像AndroidChart.HelloChart之类的,功能相当丰富,效果也很赞,但是太重了,其他的小demo又不符合要求,当然了,我写的自定义折线图的思想也有来自这些小demo,对他们表示感谢. 效果图 废话不多说,先上效果图: 效果是不是很赞,如果上图满足你的需求,那就继续往下看. 自定义折线图的步骤: 1.自定义view所需要的属性 确定所需要的自定义view的属性,

  • Android开发实现绘制淘宝收益图折线效果示例

    本文实例讲述了Android开发实现绘制淘宝收益图折线效果.分享给大家供大家参考,具体如下: 实现的效果我一会贴上,我先说下原理,我们知道要实现在canvas上画线,不就是要搞一个paint嘛,然后首先肯定要设置下paint的属性,那么画文字呢,不就是Textpaint吗,对,就是这么简单,接下来怎么画,折线图主要分为X轴和y轴,x轴表示日期,y表示收益,好,说道这里,大家应该知道怎么去做了,下面直接贴代码 这个方法是,画x,y坐标系的,以及上面的日期和收益了 private void draw

  • Android HelloChart开源库图表之折线图的实例代码

    前面我们介绍了开源图表库MPAndroidChart,请参考: Android MPAndroidChart开源库图表之折线图的实例代码 我们今天介绍的将是一个更为优秀的图表库,比MPAndroidChart性能更好,功能更完善,UI风格更美观,坐标轴更精细. 支持缩放.滑动以及平移.Zoom(pinch to zoom, double tap zoom), scroll and fling 支持自定义坐标轴(比如坐标轴位置:上下左右内部),支持自动生成坐标轴.Custom and auto-g

  • Android自定义View实现折线图效果

    下面就是结果图(每种状态用一个表情图片表示): 一.主页面的布局文件如下: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height=&quo

  • Android MPAndroidChart开源库图表之折线图的实例代码

    本文讲述了Android MPAndroidChart开源库图表之折线图的实例代码.分享给大家供大家参考,具体如下: 承接上一篇文章,请参考Android HelloChart开源库图表之折线图的实例代码 1. 将mpandroidchartlibrary-2-0-8.jar包copy到项目的libs中: 2. 定义xml文件. 3.  主要Java逻辑代码如下,注释已经都添加上了. package com.example.mpandroidlinechart; import java.util

  • Android自定义View简易折线图控件(二)

    继续练习自定义View,这次带来的是简易折线图,支持坐标点点击监听,效果如下: 画坐标轴.画刻度.画点.连线..x.y轴的数据范围是写死的 1 <= x <= 7 ,1 <= y <= 70 ..写活的话涉及到坐标轴刻度的动态计算.坐标点的坐标修改,想想就头大,这里只练习自定义View. 1.在res/values文件夹下新建attrs.xml文件,编写自定义属性: <?xml version="1.0" encoding="utf-8"

  • Android绘制动态折线图

    所谓动态折线图,就是折线图能随着手指的滑动进行动态绘制,这里很定会产生动画效果.基于这个效果,这里使用SurfaceView进行制图. 实现步奏如下: (1): 这里新建一个绘图ChartView,继承SurfaceView并实现SurfaceHolder.Callback , Runnable接口,主要绘图工作在子线程中完成. (2):现实 SurfaceHolder.Callback接口的三个方法,并在 surfaceCreated中开启子线程进行绘图. (3):重写onTouchEvent

  • MPAndroidChart开源图表库的使用介绍之饼状图、折线图和柱状图

    MPAndroidChart开源图表库之饼状图 为大家介绍一款图标开源库MPAndroidChart,它不仅可以在Android设备上绘制各种统计图表,而且可以对图表进行拖动和缩放操作,用起来非常灵活.MPAndroidChart同样拥有常用的图表类型:线型图.饼图.柱状图和散点图. mpandroidchartlibrary.jar包下载地址: https://github.com/PhilJay/MPAndroidChart/releases 下面主要实现以下饼状图: 1.从上面的地址中下载

  • Android实现折线走势图

    本文实例为大家分享了Android折线走势图的具体代码,供大家参考,具体内容如下 先来看看效果图 可以根据球的数量动态的改变自己的球半径,以及线宽 代码实现也是超级简单 //获取自定义属性 private void obtainStyledAttrs(AttributeSet attrs) { TypedArray typedArray = getContext().obtainStyledAttributes(attrs,R.styleable.High_LowChartView); mTex

  • Android开发之天气趋势折线图

    先来看下效果: 控件内容比较简单,就是一个普通的折线图,上下分别带有数字,点击的时候显示当天温度的差值. 创建一个类继承自View,并添加两个构造方法: public class TrendGraph extends View { public TrendGraph(Context context) { // 在java代码中创建调用 super(context); } public TrendGraph(Context context, AttributeSet attrs) { // 在xm

  • 详解Android图表 MPAndroidChart折线图

    1.介绍 MPAndroidChart GitHub地址 MPAndroidChart的强大之处就不在多说了,目前最新的版本是3.0.1,在新版本中很多方法都被弃用了,这个要注意一下,在网上查到的大多数资料都是关于旧版本的,今天来实现一下折线图,把过程记录下来,分享给大家. 效果图: 2.引入开源库 在项目根目录的build.gradle文件中加入如下代码 allprojects { repositories { maven { url "https://jitpack.io" } }

随机推荐