【问题标题】:BlackBerry - ButtonField with centered BitmapBlackBerry - 带有居中位图的 ButtonField
【发布时间】:2010-12-14 22:37:17
【问题描述】:

我有一个从 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);
    }
} 

如果您可以从我的 cmets 中看到 paint 方法,显然 ButtonField 0,0 位置并不完全位于按钮的最左和最上角,不知何故它被填充了未知的偏移量,因此这使得图像居中变得困难.

但是如果我从 Field 类扩展,问题就消失了,但我需要继续从 ButtonField 扩展,因为我需要 ButtonField 边框和焦点样式(蓝白色圆角矩形),我只需要显示居中的图像一个 ButtonField,并且仍然保留所有标准 ButtonField 属性。

有没有办法消除 ButtonField 上的paint方法中的填充偏移?我试过 setPadding 和 setMargin 但没有这样的运气。非常感谢!

【问题讨论】:

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


    【解决方案1】:

    在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());
    }
    

    【讨论】:

    • 我也有同样的问题..我已经尝试过你的建议,但按钮中的图像周围仍然有空白区域..
    • @Yagnesh,您是否将边框、内边距和边距设置为零?图像的形状是什么?你能说出图片和BitmapButtonField的大小吗?
    • 感谢回复,我得到了解决方案,我设置了边框,填充为零。
    猜你喜欢
    • 1970-01-01
    • 2011-02-19
    • 2011-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    相关资源
    最近更新 更多