2013-05-12 212 views
0

這是我的課。我想在我的簡單遊戲的GameEngine使用它..但我不明白這裏的問題..它不工作..drawBitmap NullPointerException異常

public class Droid { 

    private Bitmap  bitmap; 
    private int  x;  
    private int  y;  
    private boolean   touched;  
    private Speed  speed; 
    private Paint  paint; 

    public Droid(Resources resources, Bitmap bitmap, int x, int y) 
     { 
      this.bitmap = bitmap; 
      this.x = x; 
      this.y = y; 

      // create droid and load bitmap 
      bitmap = BitmapFactory.decodeResource(resources, 
        R.drawable.droid_1); 

     } 

       public void draw(Canvas canvas) 
     { 

      canvas.drawBitmap(bitmap, x - bitmap.getWidth()/2, 
        y- bitmap.getHeight()/2, paint); 
     } 



    } 

當我運行代碼,ı在draw()方法見nullpointerexception ...如何解決這個問題?感謝您的幫助......

回答

0

//我希望,我解決了這個問題。最後.. :)

公共類Droid {

private Bitmap  bitmap; 
private int  x;  
private int  y;  
private boolean   touched;  
private Speed  speed; 
private Paint  paint; 

public Droid(Resources resources, Bitmap bitmap, int x, int y) 
    { 
     paint= new Paint(); 
// this.bitmap = bitmap; // delete this part, it will work.. :))) 
    this.x = x; 
    this.y = y; 

     // create droid and load bitmap 
     bitmap = BitmapFactory.decodeResource(resources, 
       R.drawable.droid_1); 

    } 

      public void draw(Canvas canvas) 
    { 

     canvas.drawBitmap(bitmap, x - bitmap.getWidth()/2, 
       y- bitmap.getHeight()/2, paint); 
    } 



} 
0

MainActivity

public class MainActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); 
    MyView mv = new MyView(this,bmp,100,100); 
      // pass the bitmap and x and y co-ordinates to the constructor of Myview 
    setContentView(mv); // set the content to your activity 
} 
    } 

自定義視圖類

public class MyView extends View{ // should extend view 
Context c; 
private Bitmap bitmap; 
private int  x;  
private int  y; 
private Paint  paint; 
public MyView(Context context,Bitmap bmp, int i, int j) { 
    super(context); 
    // TODO Auto-generated constructor stub 
    this.c=context; 
    this.bitmap=bmp; 
    this.x=i; 
    this.y=j; 
    paint= new Paint(); 
} 
@Override 
    public void draw(Canvas canvas) // override view on draw and draw the bitmap 
    { 

    canvas.drawBitmap(bitmap, x - bitmap.getWidth()/2, 
      y- bitmap.getHeight()/2, paint); // instead of paint you can have null 
    } 
} 
+0

我試過這個:canvas.draw位圖(位圖,x - bitmap.getWidth()/ 2, y-bitmap.getHeight()/ 2,null);但它tdidnt工作.. – futuristixa 2013-05-12 08:07:02

+0

我會在幾秒鐘內更新我的答案 – Raghunandan 2013-05-12 08:11:49

+0

感謝您的幫助..ı嘗試瞭解您的代碼..公共類Droid不是一個擴展視圖類..所以這可能是一個問題。 。如果我可以解決,我會回來...... – futuristixa 2013-05-12 08:30:49