2009-11-10 31 views
0

ButtonField字段我有一個從ButtonField字段擴展類:黑莓 - 居中位圖

class BitmapButtonField extends ButtonField 
{ 
    private Bitmap _bitmap; 
    private int _buttonWidth; 
    private int _buttonHeight; 

    BitmapButtonField(Bitmap bitmap, int buttonWidth, int buttonHeight, long style) 
    {  
     super(style); 
     _buttonWidth = buttonWidth; 
     _buttonHeight = buttonHeight; 
     _bitmap = bitmap; 
    } 

    public int getPreferredHeight() 
    { 
     return _buttonHeight; 
    } 

    public int getPreferredWidth() 
    { 
     return _buttonWidth; 
    } 

    protected void layout(int width, int height) 
    { 
     setExtent(Math.min(width, getPreferredWidth()), Math.min(height, getPreferredHeight())); 
    } 

    protected void paint(Graphics graphics) 
    {  
     // THIS IS NOT CENTERED 
     int x = (getPreferredWidth() - _bitmap.getWidth()) >> 1; 
     graphics.drawBitmap(x, 0, _bitmap.getWidth(), _bitmap.getHeight(), _bitmap, 0, 0); 

     // THIS IS NOT LEFTMOST, TOPMOST 
     graphics.drawBitmap(0, 0, _bitmap.getWidth(), _bitmap.getHeight(), _bitmap, 0, 0); 
    } 
} 

如果你可以從我的paint方法的意見看,顯然是ButtonField字段0,0位置是不完全在最左邊和最按鈕的最上角,不知何故它被填充了未知的偏移量,所以這使得圖像居中困難。

但是,如果我從一個Field類擴展,問題消失,但我需要繼續從ButtonField擴展,因爲我需要ButtonField邊框和焦點樣式(藍白色圓角矩形),我只需要顯示居中圖像在ButtonField上,並且仍然保留所有的標準ButtonField屬性。

有沒有辦法消除ButtonField上paint方法中的填充偏移量?我試過setPadding和setMargin,但沒有這樣的運氣。非常感謝!

回答

0

在塗料()來定義X爲圖象偏移有一個代碼:

int x = (getPreferredWidth() - _bitmap.getWidth()) >> 1; 

這是確定,仍按鈕可以具有其它尺寸,因爲:

protected void layout(int width, int height) 
{ 
    setExtent(Math.min(width, getPreferredWidth()), 
     Math.min(height, getPreferredHeight())); 
} 

嘗試使用

protected void layout(int width, int height) 
{ 
    setExtent(getPreferredWidth(), getPreferredHeight()); 
} 
+0

我也有同樣的問題..我試着用你的建議,但仍然得到空白區周圍的圖像按鈕.. – 2012-03-21 10:43:30

+0

@ Yagnesh,您是否將邊框,填充和邊距設置爲零?圖像的形狀是什麼?你能告訴圖像和BitmapButtonField的大小嗎? – 2012-03-22 14:43:14

+0

感謝您的回覆,我得到解決方案我已設置邊框,填充爲零。 – 2012-03-23 03:32:53