gpt4 book ai didi

ios - 洪水填充,在 Swift 中只工作了一半

转载 作者:行者123 更新时间:2023-11-28 08:54:41 24 4
gpt4 key购买 nike

我在 swift 中使用以下函数时遇到问题。它旨在淹没任意区域。填充颜​​色存储在名为 floodTargetPixel 的变量中,原始颜色存储在 floodSourcePixel 中。

四种便捷方法:red() , green() , blue() , alpha() , rgba()与此处相同: Change color of certain pixels in a UIImage

(问题:)只有部分区域被填充(起点以上的部分)而不是其余部分,我错过了什么?调用代码在函数本身之后。

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

调用代码如下:

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

在 floodFill() 方法中,如果我取消注释 2 个注释行,程序会运行一段时间并在某个时候崩溃。我认为这才是真正的问题所在,因为这些行应该取消注释。

如果我排列 2 个 if block 的顺序: if (point.y >= 1.0)if (point.y <= CGFloat(imageHeight)-2.0)然后填充起点下方的部分,而不是上方的部分。

最佳答案

免责声明:我不知道swift!但一般来说,洪水填充是递归的。所以函数应该只依赖于它的参数。在 C++ 中,这将是“静态的”。但是你的函数修改了“floodPixel”,这不是一个参数。确保您的 floodFill 函数只接受参数来完成它的工作,而不是任何类/对象状态。

关于ios - 洪水填充,在 Swift 中只工作了一半,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33406773/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com