2016-04-20 429 views
1

我寫了代碼與指導移動我的背景在遊戲中,它的工作,但我的背景的大小是原創的,我想讓我的移動背景的大小,請幫助我))如何使全屏幕背景?

代碼:

public class Background extends SurfaceView implements 
    SurfaceHolder.Callback { 
private Bitmap backGround; 

public Background(Context context) { 
    super(context); 
    backGround = BitmapFactory.decodeResource(context.getResources(), 
      R.drawable.cold_planet); 
    setWillNotDraw(false); 
} 

@Override 
protected void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 
    doDrawRunning(canvas); 
    invalidate(); 
} 

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

} 

@Override 
public void surfaceCreated(SurfaceHolder holder) { 

} 

@Override 
public void surfaceDestroyed(SurfaceHolder holder) { 

} 

/** 
* Draws current state of the game Canvas. 
*/ 

private int mBGFarMoveX = 0; 
private int mBGNearMoveX = 0; 

private void doDrawRunning(Canvas canvas) { 

    // decrement the far background 
    mBGFarMoveX = mBGFarMoveX - 1; 

    // decrement the near background 
    mBGNearMoveX = mBGNearMoveX - 4; 

    // calculate the wrap factor for matching image draw 
    int newFarX = backGround.getWidth() - (-mBGFarMoveX); 

    // if we have scrolled all the way, reset to start 
    if (newFarX <= 0) { 
     mBGFarMoveX = 0; 
     // only need one draw 
     canvas.drawBitmap(backGround, mBGFarMoveX, 5000, null); 

    } else { 
     // need to draw original and wrap 
     canvas.drawBitmap(backGround, mBGFarMoveX, 0, null); 
     canvas.drawBitmap(backGround, newFarX, 0, null); 
    } 

} 

}

實施例:

example

回答

0

您應該嘗試使用爲ScaleToFit.CENTER構建的轉換矩陣。例如:

Matrix m = new Matrix(); 
m.setRectToRect(new RectF(0, 0, b.getWidth(), b.getHeight()), new RectF(0, 0, reqWidth, reqHeight), Matrix.ScaleToFit.CENTER); 
return Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m, true); 
+0

謝謝,但我應該在哪裏添加這部分代碼? – En1q0d