public class SurfaceViewTest extends SurfaceView implements SurfaceHolder.Callback {
private Timer timer;
SurfaceHolder holder;
private MyTimerTask timerTask;
//-----------------------------
private final int HEIGHT = 800;
// 要绘制的曲线的水平宽度
private final int WIDTH = 1000;
// 离屏幕左边界的起始距离
private final int X_OFFSET = 5;
// 初始化X坐标
private int cx = X_OFFSET;
// 实际的Y轴的位置
private int centerY = HEIGHT / 2;
private int cy = 0;
public SurfaceViewTest(Context context) {
super(context);
init();
}
public SurfaceViewTest(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
holder = getHolder();
holder.addCallback(this);
// 设置画布 背景透明
holder.setFormat(PixelFormat.TRANSLUCENT);
// --焦点设置----------------------------
setFocusable(true);
// 设置触屏
setFocusableInTouchMode(true);
// 设置常亮
setKeepScreenOn(true);
timer=new Timer();
timerTask = new MyTimerTask();
}
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
timer.schedule(timerTask, 30, 50);
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
timer.cancel();
timer.purge();
}
class MyTimerTask extends TimerTask {
Paint paint;
Canvas c = null;
int deltax = 0;
int count = 0;
private Queue<Point> queue;
public MyTimerTask() {
paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.STROKE);// 空心
paint.setStrokeWidth(2);
paint.setTextSize(25);
queue= new LinkedList<Point>();
}
@Override
public void run() {
cy = (int) (Math.sin((cx - X_OFFSET) / 20f) * 300) + centerY;
queue.add(new Point(cx, cy));
cx++;
count++;
if (cx > 1000) {
deltax++;
queue.poll();
}
if (count % 1 == 0) {
// 提交修改
Canvas canvas = holder.lockCanvas(new Rect(0, 0, HEIGHT,
WIDTH));
canvas.drawColor(Color.WHITE);
canvas.drawLine(X_OFFSET, centerY, WIDTH, centerY, paint);
canvas.drawLine(X_OFFSET, 40, X_OFFSET, HEIGHT, paint);
for (int i=0;i<100;i++){
canvas.drawText(""+i*10,X_OFFSET+i*50,centerY,paint);
}
// 根据X,Y坐标画点
List<Point> list = (List<Point>) queue;
Point prev = list.get(0);
for (int i = 1; i < list.size(); i++) {
Point cur = list.get(i);
canvas.drawLine(prev.x - deltax, prev.y, cur.x - deltax, cur.y, paint);
prev = cur;
}
holder.unlockCanvasAndPost(canvas);
}
}
};
}
SurfaceView 实现动态曲线
最新推荐文章于 2021-06-02 22:17:35 发布