-3

I have created a closed contour with a list of points which I want to be filled by a color.I have used boundary fill recursion algorithm but no luck the array index goes out of bounds since i cannot develop the if condition since the color inside the closed contour and color outside the contour is same.What method should i use to get the desired contour to be filled up by a specific color.Here is the code that i have tried

public class BoundaryFillAlgorithm {
public static BufferedImage toFill = MemoryPanel.Crect;
static Graphics g1 = toFill.getGraphics();
static int seedx = toFill.getWidth()/2;
static int seedy = toFill.getHeight()/2;

public static void BoundaryFill(int x,int y){

    Color old = new Color(toFill.getRGB(x, y));     
    g1.setColor(Color.BLACK);
    if(old!=Color.BLACK){       
    g1.fillOval(x, y, 1, 1);
    BoundaryFill(x+1,y);
    BoundaryFill(x,y+1);
    BoundaryFill(x-1,y);
    BoundaryFill(x,y-1);
    }
}

Here's the image

my image: rectangle

Here's the method call

BoundaryFillAlgorithm.BoundaryFill(BoundaryFillAlgorithm.seedx,BoundaryFillAlgorithm.seedy);
J. Chomel
  • 8,193
  • 15
  • 41
  • 69

3 Answers3

0
g.setColor(Color.red); // Set color to red
g.fillRect(600, 400, 100, 100);// a filled-in RED rectangle
zypa
  • 303
  • 2
  • 13
0

Why reinventing the wheel?
Graphics2D has a already a method fill(Shape). There a many classes implementing the Shape interface, especially Polygon, which you might reuse.

Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
  • what about and irregular shape like a triangle abd a rectangle fused together means one side of the rectangle is a side of the triangle – Nizam Ahmed Mar 20 '17 at 19:31
  • @NizamAhmed I don't expect problems here.With [Path](https://docs.oracle.com/javase/7/docs/api/java/awt/geom/Path2D.html) and [GeneralPath](https://docs.oracle.com/javase/7/docs/api/java/awt/geom/GeneralPath.html) you can construct shapes consisting of several subpaths. – Thomas Fritsch Mar 20 '17 at 20:06
0

Finally corrected my code heres the corrected code:

import java.awt.Graphics;
import java.awt.image.BufferedImage;

public class BoundaryFillAlgorithm {
public static BufferedImage toFill = MemoryPanel.Crect;
Graphics g1 = toFill.getGraphics();     

public BoundaryFillAlgorithm(BufferedImage toFill){
    int x = toFill.getWidth()/2-10;
    int y = toFill.getHeight()/2;
    int old = toFill.getRGB(x, y);
    this.toFill = toFill;
    fill(x,y,old);  
}

private void fill(int x,int y,int old) {
    if(x<=0) return;
    if(y<=0) return;
    if(x>=toFill.getWidth()) return;
    if(y>=toFill.getHeight())return;

    if(toFill.getRGB(x, y)!=old)return;
    toFill.setRGB(x, y, 0xFFFF0000);
    fill(x+1,y,old);
    fill(x,y+1,old);
    fill(x-1,y,old);
    fill(x,y-1,old);
    fill(x+1,y-1,old);
    fill(x+1,y+1,old);
    fill(x-1,y-1,old);
    fill(x+1,y-1,old);

}

}