package com.sxwdsoft.recyclerviewapplication; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.util.Timer; import java.util.TimerTask; /** * TODO: document your custom view class. */ public class MyView extends SurfaceView implements SurfaceHolder.Callback { private int[] Y_axis; private Timer timer; private int start; private TimerTask task; private int oldX, oldY; private int viewWidth, viewHight; public MyView(Context context) { super(context); init(); } public MyView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { getHolder().addCallback(this); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { viewWidth = getDefaultSize(300, widthMeasureSpec); viewHight = getDefaultSize(300, heightMeasureSpec); setMeasuredDimension(viewWidth, viewHight); } private Paint p, mPaint; @Override public void surfaceCreated(final SurfaceHolder holder) { p = new Paint(); p.setColor(Color.BLACK); p.setStrokeWidth(2); mPaint = new Paint(); mPaint.setColor(Color.GREEN);// 画笔为绿色 mPaint.setStrokeWidth(2);// 设置画笔粗细 //绘制坐标轴 this.timer = new Timer(); Y_axis = new int[360]; // for (int i = 0; i < Y_axis.length; i++) {// 计算正弦波 // Y_axis[i] = viewHight / 2 // - (int) (100 * Math.sin(i * Math.PI / 180)); // } for (int i = 0; i < 360; i++) { Y_axis[i] = viewHight / 2 - (int) (100 * Math.sin(i * Math.PI / 180)); } oldY = viewHight / 2; task = new TimerTask() { @Override public void run() { for (int i = start; i < Y_axis.length + start; i++) {// 计算正弦波 Y_axis[i - start] = viewHight / 2 - (int) (100 * Math.sin(i * Math.PI / 180)); } start++; if (start == Y_axis.length) start = 0; SimpleDraw(holder); } }; timer.schedule(task, 0, 5); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { timer.cancel(); task.cancel(); // holder.removeCallback(this); } /* * 绘制指定区域 */ void SimpleDraw(SurfaceHolder holder) { oldX = 0; Canvas canvas = holder.lockCanvas(new Rect(oldX, 0, oldX + viewWidth, viewHight));// 关键:获取画布 if (canvas != null) { canvas.drawColor(Color.WHITE); int y = 0; for (int i = 0; i < viewWidth; i++) {// 绘画正弦波 int scale = i / 360; if (scale >= 1) y = Y_axis[i - scale * 360]; else y = Y_axis[i]; canvas.drawLine(oldX, oldY, i, y, mPaint); oldX = i; oldY = y; } canvas.drawLine(viewWidth / 2, 0, viewWidth / 2, viewHight, p); canvas.drawLine(0, viewHight / 2, viewWidth, viewHight / 2, p); holder.unlockCanvasAndPost(canvas);// 解锁画布,提交画好的图像 } } }