"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Achieve Transparent Corners in a Rounded Rectangle with a Triangular Pointer?

How to Achieve Transparent Corners in a Rounded Rectangle with a Triangular Pointer?

Published on 2024-11-12
Browse:539

How to Achieve Transparent Corners in a Rounded Rectangle with a Triangular Pointer?

Transparent Corners in Border with Rounded Corners

In the given code, the TextBubbleBorder class paints a rounded rectangle with a triangular pointer at the bottom. However, the corners outside the rectangle extend a bit, showing the background color of the parent panel. To achieve transparent corners, we modify the paintBorder method to include an additional step:

// Paint the BG color of the parent, everywhere outside the clip
// of the text bubble.
Component parent  = c.getParent();
if (parent!=null) {
    Color bg = parent.getBackground();
    Rectangle rect = new Rectangle(0,0,width, height);
    Area borderRegion = new Area(rect);
    borderRegion.subtract(area);
    g2.setClip(borderRegion);
    g2.setColor(bg);
    g2.fillRect(0, 0, width, height);
    g2.setClip(null);
}

This code checks if the component has a parent, retrieves its background color, and creates a rectangle representing the entire border region. It then creates an Area object borderRegion that represents this rectangle. Next, it subtracts the area representing the text bubble from the borderRegion, creating an Area called clip that represents the area outside the text bubble.

With clip, the code sets the clipping region for the Graphics2D object, fills it with the parent's background color, and then resets the clipping region to draw the border itself. This ensures that the corners outside the rounded rectangle become transparent, showing the parent's background color.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3