我想在java中填充轮廓

时间:2017-03-19 16:52:57

标签: java arrays swing marvin-framework marvinproject

我创建了一个封闭的轮廓,其中包含一个我希望用颜色填充的点列表。我使用了边界填充递归算法但没有运气数组索引越界,因为我无法开发if条件,因为封闭轮廓内的颜色和轮廓外的颜色是相同的。我应该使用什么方法来获得所需的轮廓以填充特定的颜色。这是我试过的代码

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

这是图像

my image: rectangle

这是方法调用

BoundaryFillAlgorithm.BoundaryFill(BoundaryFillAlgorithm.seedx,BoundaryFillAlgorithm.seedy);

3 个答案:

答案 0 :(得分:0)

xcrun

答案 1 :(得分:0)

为什么重新发明轮子?
Graphics2D已经有一个方法fill(Shape)。 有许多实现Shape接口的类,尤其是Polygon, 您可以重复使用。

答案 2 :(得分:0)

最后纠正了我的代码,后面是纠正后的代码:

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

}

}