想做出心电图类似的效果,看了好多代码整合了一下,写好之后发现画不出来,检查也检查不出来问题。
package com.example.wivedraw;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback, Runnable {
private SurfaceHolder mSurfaceHolder;
//绘图的Canvas
private Canvas mCanvas;
//子线程标志位
private boolean mIsDrawing;
private int[] x = new int[1440];
private int[] y = new int[1440];
public int i=0;
private Paint mPaint;
private Path mPath;
public MySurfaceView(Context context) {
this(context, null);
}
public MySurfaceView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MySurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mIsDrawing = true;
x[0]=999;
y[0]=getHeight()/2;
new Thread(this).start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mIsDrawing = false;
}
@Override
public void run() {
while (mIsDrawing){
drawWive();
try {
Thread.sleep(1);
}catch (Exception e){
e.printStackTrace();
}
}
}
private void drawWive() {
//获得canvas对象
mCanvas = mSurfaceHolder.lockCanvas();
//绘制背景
mCanvas.drawColor(Color.WHITE);
int width =getWidth() ;
int height=getHeight();
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setAntiAlias(true);//抗锯齿
mPaint.setStrokeWidth(5);
mPath = new Path();
//路径起始点(0, 100)
mPath.moveTo(x[0],y[0]);
for (int j = 0; j < i; j++) {
x[j] -= 1;
}
x[i] = 1440;
y[i] = (int) (100 * Math.sin(2 * i * Math.PI / 180) + height / 2);
for (int j = 0; j <= i; j++) {
mPath.lineTo(x[j], y[j]);
}
i+=1;
if (mCanvas != null){
//释放canvas对象并提交画布
mSurfaceHolder.unlockCanvasAndPost(mCanvas);
}
}
/**
* 初始化View
*/
private void initView(){
mSurfaceHolder = getHolder();
mSurfaceHolder.addCallback(this);
setFocusable(true);
setKeepScreenOn(true);
setFocusableInTouchMode(true);
}
}
显示运行成功,但是一片空白
希望能解决问题,有余力的话麻烦帮我把代码美化一下,第一次写,所以有些地方放的不合适请谅解