我正在编写一个实现 Flood Fill 4 算法的应用程序。只要边框很厚,它就可以很好地工作。该算法在边界内填充某种颜色。我试图让边界更薄,但在这种情况下,像素能够走出边界,程序崩溃了。
洪水填充算法在直角三角形的“厚边界”区域内表现出色。但是,该算法在其他四个区域内不起作用,因为边界很薄,即发生泄漏。除了使其他寄宿生变厚外,我有什么方法可以使用吗?
这是完整的代码,它只是一个类:
import java.awt.Color;
import java.awt.Container;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MyPolygon extends JFrame {
private JLabel my;
private BufferedImage buffered;
public MyPolygon() throws InterruptedException {
createMy();
}
private void createMy() throws InterruptedException {
Container contentPane = getContentPane();
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(null);
contentPane.setSize(1200, 900);
my = new JLabel();
my.setIcon(new ImageIcon("myImage.png"));
my.setBounds(10,200, 1000, 800);
contentPane.add(my);
setSize(1200, 900);
setVisible(true);
setLocationRelativeTo(null);
Image img = ((ImageIcon) my.getIcon()).getImage();
buffered = new BufferedImage(img.getWidth(null),
img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
buffered.getGraphics().drawImage(img, 0, 0, null);
int fill = 100;
boundaryFill4(200, 215, fill, 50);
my.setIcon(new ImageIcon(buffered));
}
// Flood Fill method
public void boundaryFill4(int x, int y, int fill, int boundary) {
Color c = new Color(buffered.getRGB(x, y));
int current = c.getRed();
System.out.println(x + " " + y + " | " + current);
if ((current > boundary) && (current != fill)) {
int red = fill;
int green = fill;
int blue = fill;
c = new Color(red, green, blue);
buffered.setRGB(x, y, c.getRGB());
boundaryFill4(x + 1, y, fill, boundary);
boundaryFill4(x - 1, y, fill, boundary);
boundaryFill4(x, y + 1, fill, boundary);
boundaryFill4(x, y - 1, fill, boundary);
}
}
// Main method
public static void main(String args[]) throws InterruptedException {
MyPolygon my = new MyPolygon();
my.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}