Search code examples
javaarraysswingmarvin-frameworkmarvinproject

I want to fill a contour in java


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);

Solution

  • 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);
    
    }
    

    }