【发布时间】:2013-03-07 09:59:28
【问题描述】:
我正在 C 中为 iPhone 实现 floodfill 函数。
填充有效,虽然我有 2 个问题。
在执行以下代码几次后,手机会发出内存警告。很可能是内存泄漏。另请注意,unsigned char *data (图像数据)在填充结束时被释放()。
(较小的问题)如果我尝试将 RGB 颜色写入大于大约 (r:200,g:200,b:200,a:200 ) 我得到了奇怪的伪影发生。一种解决方法是简单地限制这些值。
我怀疑这两个问题之间可能存在相关性。
下面的代码描述了我的洪水填充算法,使用堆栈:
.h:
typedef struct {
int red;
int green;
int blue;
int alpha;
} GUIColor;
struct pixel_st {
int x;
int y;
struct pixel_st *nextPixel;
};
typedef struct pixel_st pixel;
.m:
void floodFill(CGPoint location, GUIColor tc, GUIColor rc, size_t width, size_t height, unsigned char *data){
if (isGUIColorEqual(tc, rc)) return;
pixel* aPixel = (pixel *) malloc(sizeof (struct pixel_st));
NSLog(@"sizeof aPixel : %i",(int)sizeof(aPixel));
(*aPixel).x = location.x;
(*aPixel).y = location.y;
(*aPixel).nextPixel = NULL;
int i = 0;
NSLog(@"Replacement color A%i, R%i, G%i, B%i",rc.alpha,rc.red,rc.green, rc.blue);
while (aPixel != NULL){
pixel *oldPixel_p = aPixel;
pixel currentPixel = *aPixel;
aPixel = currentPixel.nextPixel;
//Now we do some boundary checks
if (!isOutOfBounds(currentPixel.x, currentPixel.y, width, height)){
//Grab the current Pixel color
GUIColor currentColor = getGUIColorFromPixelAtLocation(CGPointMake(currentPixel.x, currentPixel.y), width, height, data);
if (isGUIColorSimilar(currentColor, tc)){
//Colors are similar, lets continue the spread
setGUIColorToPixelAtLocation(CGPointMake(currentPixel.x, currentPixel.y), rc, width,height, data);
pixel *newPixel;
if ((newPixel = (pixel*) malloc(sizeof(struct pixel_st))) != NULL) {
(*newPixel).x = currentPixel.x;
(*newPixel).y = currentPixel.y-1;
(*newPixel).nextPixel = aPixel;
aPixel = newPixel;
}
if ((newPixel = (pixel*) malloc(sizeof(struct pixel_st))) != NULL) {
(*newPixel).x = currentPixel.x;
(*newPixel).y = currentPixel.y+1;
(*newPixel).nextPixel = aPixel;
aPixel = newPixel;
}
if ((newPixel = (pixel*) malloc(sizeof(struct pixel_st))) != NULL) {
(*newPixel).x = currentPixel.x+1;
(*newPixel).y = currentPixel.y;
(*newPixel).nextPixel = aPixel;
aPixel = newPixel;
}
if ((newPixel = (pixel*) malloc(sizeof(struct pixel_st))) != NULL) {
(*newPixel).x = currentPixel.x-1;
(*newPixel).y = currentPixel.y;
(*newPixel).nextPixel = aPixel;
aPixel = newPixel;
}
free(oldPixel_p);
i ++;
if (i == width * height * 4 * 5) break;
}
}
}
free(aPixel);
}
此堆栈实现基于此处的ObjFloodFill:
https://github.com/OgreSwamp/ObjFloodFill/blob/master/src/FloodFill.m
【问题讨论】:
-
为什么要分配一次内存,然后在 while 循环中多次释放
-
堆栈基于 ObjFloodFill,我正在将其移植到我的代码中,但我对直接 C 内存管理没有太多经验,所以我不确定。
-
在页面顶部它被标记为“OgreSwamp2 年前向 ScanlineFloodfill 添加了它不起作用的评论”
-
ScanlineFloodfill 算法不起作用,但是 4-way 可以,我不确定它的内存管理是否良好
标签: objective-c c core-graphics flood-fill