BlackBerry - 具有居中位图的ButtonField

时间:2009-11-10 07:47:36

标签: user-interface graphics blackberry layout custom-controls

我有一个从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,但没有这样的运气。非常感谢!

1 个答案:

答案 0 :(得分:0)

在paint()中为图像定义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());
}