0

I was trying to create a system of shadows in Java, similar to the box-shadow used in CSS. Not knowing what technology to use in java, I tried to create it from scratch using the Graphics2D class and the result was this:

public class BoxShadow {

    public Point pos = new Point(); //Point -> (x, y)
    protected float blur;
    protected int hex; //Hex color
    protected Component parent; //Parent component
    protected Bounds bounds = new Bounds(); //Bounds -> (x, y, width, height)
    protected int alpha; //Opacity

    public BoxShadow(Point pos, float blur, int hex, int alpha) {
        if (pos != null) this.pos.copy(pos);
        this.blur = blur;
        this.alpha = alpha;
        this.hex = hex;
    }

    public void update() {
        if (parent != null) {
            bounds.copy(parent.getBounds());
        }
    }

    //Screen class is Graphics2D personalized class
    //Es. fillRect(Point p, Size s), ecc.
    public void render(Screen screen) {
        if (parent != null) {

            int red, green, blue;

            for (int i = (int) blur; i > 0; i--) {

                red = (hex >> 16) & 0xff;
                green = (hex >> 8) & 0xff;
                blue = hex & 0xff;

                screen.setColor(new Color(red, green, blue, (int) (alpha / blur * i)));
                int ii = (i - (int) blur);

                screen.fillRect(
                    bounds.x + ii + pos.x, bounds.y - 1 + (i - (int) blur) + pos.y, bounds.width - (ii << 1) + 1, 1
                );
                screen.fillRect(
                    bounds.x + ii + pos.x, bounds.y + bounds.height - ii + pos.y, bounds.width - (ii << 1) + 1, 1
                );
                screen.fillRect(
                    bounds.x + ii - 1 + pos.x, bounds.y + ii - 1 + pos.y, 1, bounds.height - (ii << 1) + 2
                );
                screen.fillRect(
                    bounds.x + bounds.width - ii + pos.x, bounds.y + ii + pos.y, 1, bounds.height - (ii << 1)
                );
            }

            red = (hex >> 16) & 0xff;
            green = (hex >> 8) & 0xff;
            blue = hex & 0xff;

            screen.setColor(new Color(red, green, blue, alpha));
            screen.fillRect(bounds.x + pos.x,bounds.y + pos.y, bounds.width, bounds.height);
        }
    }
}

This class is adaptable to a component that I have created, called Panel. So far it works decently, but if I wanted to set the Panel with a border radius? This works only if the Panel does not have a border radius, how can I do to make sure that the shadow adapts to a given radius?

mikelplhts
  • 1,181
  • 3
  • 11
  • 32
  • Take reference from this link: http://stackoverflow.com/questions/13368103/jpanel-drop-shadow – Amit Bhati Aug 24 '15 at 10:57
  • @AmitBhati But I don't use a regular `Panel` or `JPanel`. The `Panel` component cited first is a fully customizated component. – mikelplhts Aug 24 '15 at 11:05

0 Answers0