我有一个从 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);
}
}
如果您从我对绘制方法的评论中看到,显然 ButtonField 0,0 位置并不完全位于按钮的最左边和最上角,不知何故它被填充了未知的偏移量,因此这使得图像居中变得困难。
但是如果我从 Field 类扩展,问题就会消失,但我需要继续从 ButtonField 扩展,因为我需要 ButtonField 边框和焦点样式(蓝白色圆角矩形),我只需要在 ButtonField 上显示居中图像,并且仍然保留所有标准 ButtonField 属性。
有没有办法消除 ButtonField 上的绘制方法中的填充偏移量?我尝试过 setPadding 和 setMargin 但没有这样的运气。多谢!