在java中,我们要实现绘图,一般通过继承IFrame或者是在JFrame上窗体来画图,或在窗体上加入面板在上面进行画图。而android上也有几种画图方法。
1)在界面上加入一个图片组件,再在该图片组件上画图。
2)定义一个类继承View类来实现自定义画图组件,重写当中的构造方法,否则在使用时会出错。完成之后可在布局管理器中看到该自定义组件,课直接拖拽到界面上使用。
在界面上绘图会用到Bitmap位图对象可理解为内存缓冲对象,创建时定义大小和类型;Canvas画布对象,传入Bitmap对象之后,可以在界面上进行画图;Paint类对象可以理解成画笔,可以调绘图时线条大小和颜色等等。
3)定义一个类并且继承SurfaceView类,并实现Callback和Runnable接口。要重新SurfaceView类的三个构造方法,以及实现Runnable接口的run()方法,还有Callback接口的创建、改变、销毁三个方法。
在run()方法内实现绘图,锁定画布对象传给新建的画布对象,在进行绘图,因为有可能得到的是空的,所以要对异常进行一下捕捉。最后在画布完成绘图后,画布对象不为空时释放画布对象。
要实现简单移动,在线程内控制图像的坐标移动即可。
package com.example.myproject;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
MySurfaceView view = new MySurfaceView(this);
setContentView(view);
}
}
package com.example.myproject;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
public class MySurfaceView extends SurfaceView implements Callback,Runnable{
private float x,y;
private boolean runflag = true;
private SurfaceHolder holder;
private Paint paint = new Paint();
public MySurfaceView(Context context) {
this(context, null);
}
public MySurfaceView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public MySurfaceView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
holder = this.getHolder();
holder.addCallback(this);
}
public void surfaceChanged(SurfaceHolder holder, int formag, int weigth, int height) {
}
public void surfaceCreated(SurfaceHolder holder) {
//启动线程
Thread t = new Thread(this);
t.start();
}
public void surfaceDestroyed(SurfaceHolder holder) {
//停止线程
runflag = false;
}
public void run() {
while(runflag){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Canvas canvas = null;
try{
paint.setColor(Color.BLACK);
paint.setStyle(Style.FILL);
canvas = holder.lockCanvas();
canvas.drawCircle(x, y, 100, paint);
x++;
y++;
paint.setColor(Color.RED);
paint.setStyle(Style.FILL);
canvas = holder.lockCanvas();
canvas.drawCircle(x, y, 100, paint);
} catch (Exception e){
e.printStackTrace();
}finally{
if(canvas != null)
//画布对象使用完成,进行释放
holder.unlockCanvasAndPost(canvas);
}
}
}
}