Android 基于surfaceView绘制正弦曲线

package com.example.sufaceviewpractice;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class SufaceViewDemo  extends SurfaceView implements Runnable,SurfaceHolder.Callback{
	private SurfaceHolder mHolder;
	private Canvas mCanvas;
	private boolean mIsDrawing;
	private int x=1;
	private int y;
	private Path mPath;
	private Paint mPaint;

	public SufaceViewDemo(Context context) {
		super(context);
		initView();

	}

	private void initView() {
		mHolder=getHolder();
		mHolder.addCallback(this);  //注册surfaceHolder的回调方法
		setFocusable( true);
		setFocusableInTouchMode(true);
		this.setKeepScreenOn(true);

	}

	//call back  需要实现的方法

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		mIsDrawing=true;
		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){
			draw();
			x+=1;
			y=(int)(100*Math.sin(x*2*Math.PI/180)+400);
			mPath.lineTo(x, y);
		}
	}
	
	public void draw(){
		try {
			mCanvas=mHolder.lockCanvas();
			mCanvas.drawColor(Color.WHITE);
			mCanvas.drawPath(mPath, mPaint);
		} catch (Exception e) {

		}finally{
			if (mCanvas!=null){
				mHolder.unlockCanvasAndPost(mCanvas);
			}
		}
	}
}

你可能感兴趣的:(Android开发)