我正在构建一个室内导航应用程序,使用Dijkstra算法和可用的地图来指导校园内的人。当我在可用地图上绘制零件图时,我创建了一个CustomView,并按照互联网上有关如何在Canvas中绘制线条的说明进行操作。这是“MyImageView.java”的代码
public class MyImageView extends SurfaceView implements SurfaceHolder.Callback {
private CanvasThread canvasThread;
public MyImageView(Context context) {
super(context);
getHolder().addCallback(this);
canvasThread = new CanvasThread(getHolder(), this);
setFocusable(true);
}
public MyImageView(Context context, AttributeSet attrs){
super(context,attrs);
getHolder().addCallback(this);
canvasThread = new CanvasThread(getHolder(), this);
setFocusable(true);
}
protected void onDraw(Canvas canvas){
Log.d("ondraw", "ondraw");
Paint p = new Paint();
Bitmap mapImg = BitmapFactory.decodeResource(getResources(), R.drawable.map);
Bitmap mapImgResized = Bitmap.createScaledBitmap(mapImg,canvas.getWidth(),canvas.getHeight(), true);
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(mapImgResized, 0, 0, null);
p.setColor(Color.RED);
p.setStrokeWidth(6f);
p.setStyle(Paint.Style.STROKE);
canvas.drawLine(524,995,524,495,p);
canvas.drawLine(524,495,410,495,p);
canvas.drawLine(410,495,396,418,p);
canvas.drawLine(396,418,157,418,p);
canvas.drawLine(157,418,157,267,p);
canvas.drawLine(157,267,114,267,p);
canvas.drawLine(114,267,114,244,p);
canvas.drawLine(114,244,72,244,p);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
canvasThread.setRunning(true);
canvasThread.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
canvasThread.setRunning(false);
while(retry){
try {
canvasThread.join();
retry = false;
}
catch (InterruptedException e){
}
}
}
}
这是“CanvasThread.java”的代码
public class CanvasThread extends Thread {
private SurfaceHolder surfaceHolder;
private MyImageView myImageView;
private boolean run = false;
public CanvasThread(SurfaceHolder s, MyImageView m){
surfaceHolder = s;
myImageView = m;
}
public void setRunning(boolean r){
run = r;
}
public void run(){
Canvas c;
while(run){
c = null;
try
{
c = surfaceHolder.lockCanvas(null);
synchronized (surfaceHolder){
myImageView.onDraw(c);
}
}
finally {
if(c!=null){
surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
ImageView的XML部分
<?xml version="1.0" encoding="utf-8"?>
<com.example.borntowin.draft.MyImageView
android:id="@+id/main_imagemap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="80dp"/>
此代码工作正常,但在结果中我可以看到只要模拟器正在运行,onDraw方法就会运行。有人能为我解释原因吗?它与CanvasThread有什么关系吗?我使用的是Android Studio 1.5。