Rounded Panel clipping image
I have a rounded panel that is inside a Panel with a BackgroundImage painted over it using PaintComponent. Problem is, this happens:
My actual code is:
For the Background Panel:
public class JPanelBackground extends JPanel {
private BufferedImage backgroundImage;
public JPanelBackground(String imagePath) throws IOException {
backgroundImage = ImageIO.read(new File(imagePath));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int panelWidth = getWidth();
int panelHeight = getHeight();
// Obtener el ancho y alto de la imagen de fondo
int imageWidth = backgroundImage.getWidth();
int imageHeight = backgroundImage.getHeight();
// Calcular la relación de aspecto de la imagen
double aspectRatio = (double) imageWidth / imageHeight;
// Calcular el ancho y alto de la imagen para que se ajuste al panel manteniendo la relación de aspecto
int scaledWidth = panelWidth;
int scaledHeight = (int) (panelWidth / aspectRatio);
// Si la altura escalada es menor que la altura del panel, recalcula el ancho y alto para ajustar a la altura del panel
if (scaledHeight < panelHeight) {
scaledHeight = panelHeight;
scaledWidth = (int) (panelHeight * aspectRatio);
}
// Calcular las coordenadas de dibujo para centrar la imagen
int x = (panelWidth - scaledWidth) / 2;
int y = (panelHeight - scaledHeight) / 2;
// Dibujar la imagen de fondo escalada y centrada en el panel
g.drawImage(backgroundImage, x, y, scaledWidth, scaledHeight, this);
}
}
For the Rounded Panel;
putClientProperty( FlatClientProperties.STYLE, "arc: 90" ); setBackground( Color.red);
Is this a problem, or is this a Skill Issue from my behalf?
Panels fills the whole background if they are opaque, which is the default.
So you need to make the rounded panel non-opaque (e.g. roundedPanel.setOpaque(false)).
The downside is that FlatLaf no longer paints the rounded "red" background. You need to paint that yourself ATM 😉
Maybe I should change FlatLaf so that panels with rounded corners are painted even if they are non-opaque...
Oh thanks!
I've changed panel's background painting behavior: rounded background is now always painted, even if panel is non-opaque.
Try latest 3.5-SNAPSHOT: https://github.com/JFormDesigner/FlatLaf#snapshots