您的位置:首页 > 移动开发 > Android开发

Android 基于surfaceView绘制正弦曲线

2016-07-07 16:00 483 查看
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);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: