简体   繁体   English

如何绘制中间切出一个圆的矩形?

[英]How do I draw a rectangle with a circle cut out in the middle?

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. 嗨,我需要绘制一个图像,并且我只希望其中一部分可见(圆形),我首先计划的是绘制图像(占据整个JFrame),然后用黑色矩形覆盖它,然后绘制一个中心上完全透明的圆圈,但是它不起作用,因为您只能看到我在图像上绘制的黑色矩形。 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);

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);

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM