2015-04-29 20 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

相關問題