2014-09-28 18 views
-1

基本上我想用drawBitmap方法替換drawcircle方法。這個想法是用我已經導入的圖像替換圓圈。Android中的位圖canvas.drawBitmap方法

這裏是我的資源的方法

// Create the bitmap object using BitmapFactory 
    // Access the application resource, and then retrieve the drawable 
    Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.ball); 

我想改變畫圓的方法,而是用drawbitmap更換。

// Create a new class extended from the View class 
class GameView extends View 
{ 
    Paint paint = new Paint(); 

    // Constructor 
    public GameView(Context context) 
    { 
     super(context); 
     setFocusable(true); 
    } 

    // Override the onDraw method of the View class to configure 
    public void onDraw(Canvas canvas) 
    { 
     // Configure the paint which will be used to draw the view 
     paint.setStyle(Paint.Style.FILL); 
     paint.setAntiAlias(true); 
     // If the game is over 
     if (isLose) 
     { 
      paint.setColor(Color.RED); 
      paint.setTextSize(40); 
      canvas.drawText("Game Over", 50, 200, paint); 
     } 
     // Otherwise 
     else 
     { 
      // set the color of the ball 
      paint.setColor(Color.rgb(240, 240, 80)); 
      canvas.drawCircle(ballX, ballY, BALL_SIZE, paint); 
      // set the color of the racket 
      paint.setColor(Color.rgb(80, 80, 200)); 
      canvas.drawRect(racketX, racketY, racketX + RACKET_WIDTH, 
        racketY + RACKET_HEIGHT, paint); 
     } 
    } 

我知道我必須以某種方式取代canvas.drawCircle但每次我已經嘗試到目前爲止還沒有工作。 如果有人能幫助,將不勝感激。

+0

我希望用看起來像一個球的圖像替換canvas.drawCircle,而不是畫一個圓。 – user3584935 2014-09-28 07:13:16

回答

0

更改下面的代碼:

// set the color of the ball 
    paint.setColor(Color.rgb(240, 240, 80)); 
    canvas.drawCircle(ballX, ballY, BALL_SIZE, paint); 

到:

canvas.drawBitmap(bitmap, null, destRect, null); 

在上面的代碼,位圖指的是你在你的代碼中創建的一個,並且desRect是一個矩形,決定在哪裏繪製該位圖。它可能是這樣計算的:

Rect destRect = new Rect(ballX - BALL_SIZE, ballY - BALL_SIZE, ballX + BALL_SIZE, ballY + BALL_SIZE); 

記得在onDraw方法外計算它,以防出現效率問題。

相關問題