1
votes

I am having trouble with the following function in swift. It is meant to flood-fill an arbitrary area. The filling color is stored in a variable called floodTargetPixel and the original in floodSourcePixel.

The four convenience methods: red(), green(), blue(), alpha(), rgba() are the same as here: Change color of certain pixels in a UIImage

(Problem:)Only part of the area is filled (the part above the starting point) and not the rest, what am I missing? The calling code is after the function itself.

    func floodFill(point:CGPoint)
    {
        let pixel = floodPixel.memory

        if (red(pixel) == floodTargetPixel[0] && green(pixel) == floodTargetPixel[1] &&
            blue(pixel) == floodTargetPixel[2] && alpha(pixel) == floodTargetPixel[3]) {
                return
        }

        if (red(pixel) != floodSourcePixel[0] || green(pixel) != floodSourcePixel[1] ||
            blue(pixel) != floodSourcePixel[2] || alpha(pixel) != floodSourcePixel[3]) {
                return
        }

        floodPixel.memory = rgba(red: floodTargetPixel[0], green: floodTargetPixel[1],
            blue: floodTargetPixel[2], alpha: floodTargetPixel[3])

        if (point.y >= 1.0) {
            floodPixel -= imageWidth
            self.floodFill(CGPointMake(point.x,point.y-1.0))
//            floodPixel += imageWidth
        }
        if (point.y <= CGFloat(imageHeight)-2.0) {
            floodPixel += imageWidth
            self.floodFill(CGPointMake(point.x,point.y+1.0))
//            floodPixel -= imageWidth
        }
        if (point.x >= 1.0) {
            floodPixel--
            self.floodFill(CGPointMake(point.x-1.0,point.y))
            floodPixel++
        }
        if (point.x <= CGFloat(imageWidth)-2.0) {
            floodPixel++
            self.floodFill(CGPointMake(point.x+1.0,point.y))
            floodPixel--
        }
    }

Here is the calling code:

…….
    pixelBuffer = UnsafeMutablePointer<UInt32>(CGBitmapContextGetData(context))
    var pixelPos:Int = imageWidth * Int(point.y) + Int(point.x)
    floodPixel = pixelBuffer!
    floodPixel += pixelPos
    self.floodFill(point)
…….

In the floodFill() method, if I uncomment the 2 commented lines, the program runs for a while and crashes at some point. I presume this is where the real issue is, because those lines should be uncommented.

If I permute the order of the 2 if-blocks: if (point.y >= 1.0) and if (point.y <= CGFloat(imageHeight)-2.0) then the part below the starting point is filled, instead the part above.

1

1 Answers

0
votes

Disclaimer: I do not know swift! But in general, a flood fill is recursive. So the function should be only dependent on it's arguments. In C++ that would be "static". But your function modifies "floodPixel" which is not an argument. Make sure your floodFill function only takes arguments to do it's work, not ANY class/object state.