BlackBerry - ButtonField with centered Bitmap

这一生的挚爱 提交于 2019-12-04 02:35:33

问题


I have a class that extends from 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);
    }
} 

If you could see from my comments on the paint method, clearly the ButtonField 0,0 position is not exactly in leftmost and topmost corner of the button, somehow it is padded with unknown offset, so this makes centering the image is difficult.

But if I extend from a Field class, the problem goes away, but I need to keep extending from ButtonField since I need the ButtonField border and focus style (blue-white rounded rectangle), I just need to display centered image on a ButtonField, and still retaining all of the standard ButtonField attributes.

Is there a way to eliminate the padded offset in paint method on a ButtonField? I've tried setPadding and setMargin but no such luck. Thanks a lot!


回答1:


In paint() to define x offset for image there is a code:

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

It is ok, still button can have other size, because of:

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

Try to use

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


来源:https://stackoverflow.com/questions/1706241/blackberry-buttonfield-with-centered-bitmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!