参考:http://byandby.iteye.com/blog/824535
http://www.himigame.com/android-game/306.html
package com.gdseed.canvastestboard;
import java.net.ContentHandler;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class MyView extends SurfaceView implements SurfaceHolder.Callback {
private int mMoveX = 0;
private SurfaceHolder holder;
private MyThread myThread;
/*
在布局文件中的MyView
public MyView(Context context, AttributeSet attrs) {
super(context);
holder = this.getHolder();
holder.addCallback(this);
myThread = new MyThread(holder);// 创建一个绘图线程
}
*/
public MyView(Context context) {
super(context);
holder = this.getHolder();
holder.addCallback(this);
myThread = new MyThread(holder);// 创建一个绘图线程
}
public void onRedraw() {
new MyThread(holder).start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
myThread.start();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return super.onTouchEvent(event);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
myThread.isRun = true;
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
myThread.isRun = false;
}
// 线程内部类
class MyThread extends Thread {
private SurfaceHolder holder;
public boolean isRun;
public MyThread(SurfaceHolder holder) {
this.holder = holder;
isRun = true;
}
@Override
public void run() {
while (isRun) {
Canvas c = null;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
synchronized (holder) {
c = holder.lockCanvas();
if (c != null) {
c.drawColor(Color.WHITE);
DrawTools.drawTab(c, mMoveX);
mMoveX = 0;
} else {
Log.d("Zhangjd", "c is null");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (c != null) {
holder.unlockCanvasAndPost(c);// 结束锁定画图,并提交改变。
}
isRun = false;
}
}
}
}
}
开始绘图:
画笔设置:
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStyle(Style.FILL);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(1.0f);
paint.setTextSize(12);
绘制矩形:
mCanvas.drawRect(left, top, bottom,right, paint);
绘制线条:
mCanvas.drawLine(x1 , y1, x2, y2, paint);
绘制文字:
canvas.drawText(text,x,ypaint);