Search code examples
javaandroidlibgdxscene2d

Bounds of an ImageButton


I have a button (reloadButton) which is an ImageButton

I want to setBounds() to it but the problem is its ImageButtonStyle.imageUp and ImageButtonStyle.imageDown are rounded images and I don't want to make the bounds rectangle as this button can be touched

How can I setBounds to this button ?

Here is my code

TextureRegion buttonUp = Assets.getTextureRegion(Assets.getTextureAtlas(Assets.reloadButton), "up"); 

TextureRegion buttonDown = Assets.getTextureRegion(Assets.getTextureAtlas(Assets.reloadButton), "down"); 

ImageButton.ImageButtonStyle buttonStyle = new ImageButton.ImageButtonStyle(); 

buttonStyle.imageUp = new TextureRegionDrawable(buttonUp); 

buttonStyle.imageDown = new TextureRegionDrawable(buttonDown); 

reloadButton = new ImageButton(buttonStyle);

 // reloadButton.addListener()

Solution

  • Actor bounds are always a rectangle. If you want to test a different shape, override the hit method of your Actor. For example, for a rounded rectangle, subclass ImageButton and do this (where rad is the corner radius):

    @Override
    public Actor hit (float x, float y, boolean touchable) {
        Actor hit = super.hit(x, y, touchable); //is in rectangle
    
        if (hit != null){ //reject corners if necessary
            boolean keep = true;
            if (x < rad){
                if (y < rad) keep = inCircle(x, y, rad, rad, rad);
                else if (y > getHeight() - rad) keep = inCircle(x, y, rad, getHeight() - rad, rad);
            } else if (x > getWidth() - rad){
                if (y < rad) keep = inCircle(x, y, getWidth() - rad, rad, rad);
                else if (y > getHeight() - rad) keep = inCircle(x, y, getWidth() - rad, getHeight() - rad, rad);
            }
            if (!keep) hit = null;
        }
        return hit;
    }
    
    private boolean inCircle(float x, float y, float centerX, float centerY, float radius) {
        float dx = x - centerX;
        float dy = y - centerY;
        return dx * dx + dy * dy <= radius * radius;
    }