java – How to fill an area with color?

Question:

I am creating a graphical editor in Java.

How do I fill an area with color? I wrote a function that enters coordinates into an array, and then forms a shape, but it does not work.

The code:

``````public Polygon FloodFill (BufferedImage ima,Point node, Color fillcolor, int Oldcolor){
Point a [] = new Point[1000];
Point n;
n=node;
int x = n.x;
int y = n.y;
int i=0;
while(a[i]!=null){
if(ima.getRGB(x, y)==oldcolor){
a[i]=n; }

if(ima.getRGB(x-1, y)==oldcolor){
n.setLocation(x-1, y);
a[i+1]=n;}

if(ima.getRGB(x+1, y)==oldcolor){
n.setLocation(x+1, y);
a[i+2]=n;}

if(ima.getRGB(x, y-1)==oldcolor){
n.setLocation(x, y-1);
a[i+3]=n;}

if(ima.getRGB(x, y+1)==oldcolor){
n.setLocation(x, y+1);
a[i+4]=n;}
i=i+1;
}
int yMas [] = new int[1000];
int xMas [] = new int[1000];
int d=0;
for(i=0;a[i]!=null;i++){
yMas[i]=a[i].x;
xMas[i]=a[i].y;
d=d+1;
}
Polygon poly = new Polygon(xMas, yMas, d);
return poly;}
``````

This is how I call the function:

``````Polygon p; p = FloodFill(imag,n,maincolor,oldcolor);
g2.fillPolygon(p);
``````

The fill function of a known shape in swing is implemented through the fill method

``````g2D.fill(Shape s)
``````

Accordingly, you need to define the shape yourself, create it and fill it with the fill method. You can define your shape by comparing the color of adjacent pixels with white (if your background is of course white), and remembering them, and finally forming them into a shape.

Scroll to Top