2014-01-20 130 views
0

我正在製作一個屏幕,我需要我的gBall在屏幕中心對齊。代碼如下: 代碼如下。如何將畫布對象與屏幕中心對齊?

@Override 
    protected void onDraw(Canvas canvas) { 
    // TODO Auto-generated method stub 
    super.onDraw(canvas); 
    canvas.drawColor(Color.RED); 

    Paint textPaint = new Paint(); 
    textPaint.setColor(Color.BLUE); 
    textPaint.setTextAlign(Align.CENTER); 
    textPaint.setTextSize(canvas.getWidth()/7); 
    textPaint.setTypeface(font); 
    canvas.drawText("MY Text", (canvas.getWidth()/2), 
      (float) (canvas.getHeight() * 0.75), textPaint); 
    canvas.drawBitmap(gball, 0, (float) (canvas.getHeight() * .25), null);//This is where i need help 
} 

但我得到它對齊屏幕左側,任何人都可以幫忙嗎?

回答

-1

明白了這段代碼吧!

canvas.drawBitmap(gball, (canvas.getWidth()/2-(gball.getWidth()/2)), (float) (canvas.getHeight() * .25), null); 
3

您在屏幕的左側得到它,因爲你的X值設置爲0,它應該是

int startX= (canvas.getWidth()-gBall.getWidth())/2;//for horisontal position 
    int startY=(canvas.getHeight()-gBall.getHeight())/2;//for vertical position 
    canvas.drawBitmap(gball, startX, startY, null); 

另外,不要初始化的onDraw您paint()方法。

+0

with canvas.getHeigh()* 0.25你不會讓你的位圖垂直居中 – Eddy

相關問題