2009-11-10 32 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