The reason why you can only focus the transparent parts of an image is because (as far as I know) drawFocus
is fired before paint
, causing the bitmap to be drawn last.
I think this solution is what you're looking for. If you want something other than a solid colour as the border, you can play around with the BorderFactory
.
class TouchBitmapField extends BitmapField
{
Bitmap bitmap;
Border defaultBorder;
Border focusBorder;
public TouchBitmapField(Bitmap startBitmap, long style)
{
super(startBitmap, style | FOCUSABLE);
bitmap = startBitmap;
XYEdges thickness = new XYEdges(5, 5, 5, 5);
XYEdges colours = new XYEdges(0xff0000, 0xff0000, 0xff0000, 0xff0000);
XYEdges alpha = new XYEdges(0, 0, 0, 0);
// Transparent border used by default, so that adding the focus border does not resize the view
defaultBorder = BorderFactory.createSimpleBorder(thickness, colours, alpha, Border.STYLE_SOLID);
focusBorder = BorderFactory.createSimpleBorder(thickness, colours, Border.STYLE_SOLID);
setBorder(defaultBorder);
}
protected void drawFocus(Graphics graphics, boolean on)
{
// Override default blue highlight
}
protected void onFocus(int direction)
{
super.onFocus(direction);
setBorder(focusBorder);
}
protected void onUnfocus()
{
super.onUnfocus();
setBorder(defaultBorder);
}
}
If you want your border to be overlapping your image, you can override your paint
method and draw as you want.
protected void paint(Graphics graphics)
{
super.paint(graphics);
if(isFocus())
{
int tempCol = graphics.getColor();
int tempAlpha = graphics.getGlobalAlpha();
graphics.setColor(0xff0000);
graphics.setGlobalAlpha(128);
for(int i = 0; i < 5; i++)
{
graphics.drawRect(i, i, getWidth() - i * 2, getHeight() - i * 2);
}
// Reset back to original state
graphics.setColor(tempCol);
graphics.setGlobalAlpha(tempAlpha);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…