Question

Hi I need to draw an image and I want only a portion of it to be visible (circle shape) what I planned first was to draw the image (takes up the whole JFrame), then cover it with a black rectangle and then draw a completely transparent circle over the center, but it does not work because you can only see the black rectangle i drew over the image. My second approach is to draw a black rectangle with a circle cut out in the center, so only a portion of the image can be seen. How do I do this? Is there another way to do this? Thanks

//the transparent approach
int mat[][] = {{0, 0, 0}, {0, 1, 0}, {0, 0, 0};

for (int r = 0; r < mat.length; r++) {
    for (int c = 0; c < mat[r].length; c++) {
        if (mat[r][c] == 0) g2d.setPaint(Color.RED)
        else if (mat[r][c] == 1) g2d.setPaint(Color.BLACK)
        g2d.fillRect(r * 10, c * 10, 10, 10);
    }
}
g2d.setPaint(Color.DARK_GRAY);
g2d.fillRect(0, 0, panel.getWidth(), panel.getHeight());

g2d.setPaint(new Color(0f, 0f, 0f, .100f));
g2d.fillOval(0, 0, 100, 100);
Was it helpful?

Solution

If you want to draw a black rectangle with a circle cut out you could try doing something like this:


Graphics2D g2d = (Graphics2D) g;
Area a = new Area(new Rectangle(50, 50, 100, 100));
a.subtract(new Area(new Ellipse2D.Double(75, 75, 50, 50)));
g2d.fill(a);

OTHER TIPS

Something like

class Rect extends JComponent {
    public void paint(Graphics g) {
        g.setColor(Color.BLACK);
        g.drawRect (100, 100, 500, 500);     
        g.setColor(Color.WHITE);
        g.fillOval(150, 150, 250, 250);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top