2015-04-29 19 views
2

我有一个自定义的SurfaceView和一个绘制背景和位图的方法doDraw()。问题是,当我运行此我得到一个错误画布对象必须是以前由lockCanvas返回的同一个实例

产生的原因:java.lang.IllegalArgumentException异常:画布对象必须是先前被lockCanvas返回相同的实例

我没有看到为什么发生这种情况。我没有在我的代码中的任何其他地方声明任何其他画布。我只有两个其他类,MainActivity和SurfaceViewExample。 MainActivity只是有意打开SurfaceViewExample,而SurfaceViewExample只是有一些按钮调用的方法。

OurView类:

package com.thatoneprogrammerkid.gameminimum; 

import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.Canvas; 
import android.util.AttributeSet; 
import android.view.SurfaceHolder; 
import android.view.SurfaceView; 

public class OurView extends SurfaceView implements SurfaceHolder.Callback { 

    private SurfaceHolder holder; 
    private Bitmap testimg; 
    public int xCoord = 500; 
    public int yCoord = 500; 

    public OurView(Context context) { 
     super(context); 
     init(); 
    } 

    public OurView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     init(); 
    } 

    public OurView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     init(); 
    } 

    private void init() { 
     holder = getHolder(); 
     holder.addCallback(this); 
     testimg = BitmapFactory.decodeResource(getResources(),R.drawable.testimg); 
    } 

    void moveImage(int xChange, int yChange) { 
     xCoord += xChange; 
     yCoord += yChange; 
     doDraw(); 
    } 

    void doDraw() { 
     Canvas myCanvas = holder.lockCanvas(); 
     if (myCanvas != null) { 
      myCanvas.drawARGB(255, 55, 255, 255); 
      myCanvas.drawBitmap(testimg, xCoord, yCoord, null); 
     } 
     holder.unlockCanvasAndPost(myCanvas); 
    } 

    @Override 
    public void surfaceCreated(final SurfaceHolder holder) { 
     doDraw(); 
    } 

    @Override 
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} 


    @Override 
    public void surfaceDestroyed(SurfaceHolder holder) {} 

} 

回答

6

移动unlockCanvasAndPost()if (myCanvas != null) {语句中。我的猜测是lockCanvas()返回null,并且您试图解锁空引用。

看着the source code,测试“是否一样”出现在“完全锁定”的测试之前 - 并且mCanvas被初始化为非空值。

+0

感谢您的帮助!这解决了我的问题! – WD40

相关问题