在Java中,有Graphics2D.fillRect(x, y, width, height)函数。在我的程序中,我正在寻找类似但完全相反的东西。
我需要填充屏幕上的所有内容,除了这个特定的x、y、宽度、高度,有点像反填充矩形。是否有我忽略的内置函数,或者您能给我指出创建该函数的正确方向吗?
不是必需的,但如果它可以与其他 Java 2D 形状一起使用,那就太好了。
最佳答案
有几种方法可以实现,最简单的可能是使用
java.awt.geom.Area
这是一个高度通用的 Shape
实现,例如,它允许您添加和减去 Area
...
我让填充颜色稍微半透明以证明这一点;)
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/