gpt4 book ai didi

Java anti fillRect(填充所述矩形之外的所有内容)

转载 作者:行者123 更新时间:2023-11-29 03:17:50 25 4
gpt4 key购买 nike

在 Java 中,有 Graphics2D.fillRect(x, y, width, height) 函数。在我的程序中,我正在寻找类似但完全相反的东西。

我需要填充屏幕上的所有内容,除了这个特定的 x、y、宽度、高度,有点像反填充矩形。是否有我忽略的内置功能,或者您能指出正确的方向来创建一个功能吗?

不是必需的,但如果它可以与其他 Java 2D 形状一起使用,那将是一个不错的奖励。

最佳答案

有几种方法可以实现,最简单的可能是使用java.awt.geom.Area,这是一个高度通用的 Shape 实现,例如,它允许您从中添加和减去 Area ...

Clip

为了证明这一点,我让填充颜色略微半透明 ;)

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Area;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class CutExample {

public static void main(String[] args) {
new CutExample();
}

public CutExample() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

private BufferedImage img;

public TestPane() {
try {
img = ImageIO.read(...);
} catch (IOException ex) {
Logger.getLogger(CutExample.class.getName()).log(Level.SEVERE, null, ex);
}
}

@Override
public Dimension getPreferredSize() {
return img == null ? new Dimension(200, 200) : new Dimension(img.getWidth(), img.getHeight());
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (img != null) {
int x = (getWidth() - img.getWidth()) / 2;
int y = (getHeight() - img.getWidth()) / 2;
g2d.drawImage(img, x, y, this);

Area outter = new Area(new Rectangle(0, 0, getWidth(), getHeight()));
x = (getWidth() / 2) - 100;
y = (getHeight() / 2) - 100;
Rectangle inner = new Rectangle(x, y, 200, 200);
outter.subtract(new Area(inner));

g2d.setColor(new Color(0, 0, 0, 192));
g2d.fill(outter);
}
g2d.dispose();
}

}

}

我还应该提一下,您可以使用您想要的任何其他 Shape...

关于Java anti fillRect(填充所述矩形之外的所有内容),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25478376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com