參考自:手把手教你打造一個心電圖效果View Android自定義Viewhtml
動態心電圖詳見接收數據實時更新的波狀曲線圖android
效果圖canvas
佈局:安全
<?xml version="1.0" encoding="utf-8"?>
<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="match_parent" android:padding="20dp" tools:context="com.wingsofts.cardiograph.MainActivity">
<View android:layout_width="match_parent" android:layout_height="300dp" android:background="#000000" />
<com.wingsofts.cardiograph.PathView android:layout_width="match_parent" android:layout_height="300dp" />
</RelativeLayout>
自定義控件微信
import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.util.AttributeSet; import android.view.View; public class PathView extends View { //畫筆
protected Paint paint; //心電圖折線
protected Path path; //自身的大小
private int width, height; //折現的顏色
private int lineColor = Color.parseColor("#76f112"); public PathView(Context context) { this(context, null); } public PathView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public PathView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); paint = new Paint(); path = new Path(); } private void drawPath(Canvas canvas) { // 重置path
path.reset(); //用path模擬一個心電圖樣式 //1.初始位置x=0,y在中間
path.moveTo(0, height / 2); int tmp = 0; for (int i = 0; i < 10; i++) { //平移
path.lineTo(tmp + 100, height / 2); //上滑
path.lineTo(tmp + 120, height / 2 - 100); //下滑
path.lineTo(tmp + 140, height / 2 + 100); //上滑
path.lineTo(tmp + 160, height / 2 - 200); //下滑
path.lineTo(tmp + 180, height / 2 + 200); //回到中間
path.lineTo(tmp + 200, height / 2); //平滑
path.lineTo(tmp + 300, height / 2); //x座標增長到第二次循環開始的地方
tmp = tmp + 300; } //設置畫筆style
paint.setStyle(Paint.Style.STROKE); paint.setColor(lineColor); paint.setStrokeWidth(5); canvas.drawPath(path, paint); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { width = w; height = h; super.onSizeChanged(w, h, oldw, oldh); } @Override protected void onDraw(Canvas canvas) { drawPath(canvas);
//x軸滑動速度 scrollBy(1, 0);
//非UI線程下刷新佈局,由於UI線程不是線程安全的 postInvalidateDelayed(10); } }
activityapp
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
最重要的就是Path這個類和moveTo()/lineTo()方法ide
歡迎關注個人微信公衆號:安卓圈佈局