前言
遇到一个要实时显示心电图的项目,用Graphics会比较方便,记录下来。
效果
源码
实际使用把
#region
删掉。
心电图宽度高度由挂载组件的Node决定。
线的粗细颜色在Graphics
组件内调节。
需要自己将值映射到0-100的区间内再调用addPoint(YourNumber)
const {ccclass, property} = cc._decorator;
/**
* 心电图
* 需要自己将值映射到0-100的区间内再传入
* 数据个数为双数
*
* @export
* @class Electrocardiogram
* @extends {cc.Component}
*/
@ccclass
export default class Electrocardiogram extends cc.Component {
/**
* 渲染组件
*
* @type {cc.Graphics}
* @memberof Electrocardiogram
*/
@property(cc.Graphics)
Graphic: cc.Graphics = null;
/**
* 保留多少个数据
*
* @type {number}
* @memberof Electrocardiogram
*/
@property(Number)
numCount: number = 10;
/**
* 保留的数据
*
* @type {number[]}
* @memberof Electrocardiogram
*/
yArray:number[] = [];
scaleX:number = 0;
scaleY:number = 0;
/**
* 中间值
*
* @type {number}
* @memberof Electrocardiogram
*/
hafCount:number = 0;
// LIFE-CYCLE CALLBACKS:
// onLoad () {}
start()
{
this.scaleX = this.node.width/this.numCount;
this.scaleY = this.node.height*0.01;
this.hafCount = this.numCount/2;
}
addPoint(y:number)
{
//如果大于则移除
if(this.yArray.length > this.numCount)
{
this.yArray.shift();
}
this.yArray.push(y);
//重新绘制
this.Graphic.clear();
if(this.yArray.length<1)
{
return;
}
const value0 = this.yArray[0];
const y0 = (value0-50)*this.scaleY;
this.Graphic.moveTo(((this.yArray.length-1)- this.hafCount)*this.scaleX,y0);
for (let index = 0; index <this.yArray.length ; index++) {
const element = this.yArray[index];
let x = (((this.yArray.length-1)- this.hafCount)-index)*this.scaleX;
let y = (element-50)*this.scaleY;
this.Graphic.lineTo(x,y);
this.Graphic.stroke();
}
}
//#region 测试
timer=0;
update (dt) {
this.timer+=dt;
if (this.timer>0.2) {
this.timer=0;
this.addPoint(Math.random()*100);
}
}
//#endregion
}
参数设置
使用一张纯色背景(Background),配合上层的Graphics实现最终效果。