Android 特效View第四弹之折线图 心率图
<FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" > <com.example.empty.ChartView android:id="@+id/chart" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" /> </FrameLayout>
package com.example.empty; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.util.AttributeSet; import android.view.View; public class ChartView extends View{ private List mPointList = new ArrayList(); private int mPointY = 0; private Paint mPoint = new Paint(); //画笔 public ChartView(Context context, AttributeSet attrs) { // TODO Auto-generated constructor stub this(context, attrs, 0); } public ChartView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); // TODO Auto-generated constructor stub //初始化画笔 mPoint.setColor(getContext().getResources().getColor( R.color.color_tiny_blue)); mPoint.setStrokeWidth(2.0f); mPoint.setAntiAlias(true); } @Override protected void onDraw(Canvas paramCanvas) { super.onDraw(paramCanvas); //mPointY = (int) (Math.random() * 100); if (mPointList.size() >= 2) { for (int k = 0; k < -1 + mPointList.size(); k++) { paramCanvas.drawLine(((Point) mPointList.get(k)).x, ((Point) mPointList.get(k)).y, ((Point) mPointList.get(k + 1)).x, ((Point) mPointList.get(k + 1)).y, mPoint); } } Point localPoint1 = new Point(getWidth(), mPointY); int i = mPointList.size(); int j = 0; if (i > 101) { //最多绘制100个点,多余的出栈 mPointList.remove(0); while (j < 100) { Point localPoint3 = (Point) mPointList.get(j); localPoint3.x = (-7 + localPoint3.x); j++; } mPointList.add(localPoint1); return; } while (j < mPointList.size()) { //每新产生使前面的每一个点左移7 Point localPoint2 = (Point) mPointList.get(j); localPoint2.x = (-7 + localPoint2.x); j++; } mPointList.add(localPoint1); } public final void ClearList() { mPointList.clear(); } public final void AddPointToList(int paramInt) { mPointY = paramInt; invalidate();//重绘 } public void stop(){ mPointList.clear(); invalidate(); } }
启动绘图
mChartView = (ChartView)findViewById(R.id.chart); Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { Message msg = new Message(); mHandler.sendMessage(msg); } }; timer.schedule(task,1,300); private Handler mHandler = new Handler() { @Override public void dispatchMessage(Message msg) { mChartView.AddPointToList((int) (Math.random() * 100)); } };
上面的开启折线绘图只是给大家一个案例,具体效果大家依照自己需要开发。
这里只简单解释一下,折线图原理。
其实这里我们只是利用了画笔画线的原理,每当我们接收到一个新的绘制点时,我们移动之前已经存在的所有点,并把重新他们连接在一起,并把它们重新绘制出来
时间: 2024-11-07 17:10:43