我试图通过遍历缓冲区中的每个像素并根据 const char * 中的字符为其分配颜色来创建图像,当我尝试将图像添加到 ImageView 时,出现 EXC_BAD_ACCESS 错误.请帮忙。
+ (UIImage *)imageEncryptingString:(NSString *)string{
NSUInteger width = string.length;
NSUInteger height = string.length;
NSInteger dataLength = width * height * 4;
UInt8 *data = (UInt8*)malloc(dataLength * sizeof(UInt8));
const char * cryptoString = [string UTF8String];
float red = 0.0f;
float green = 0.5f;
float blue = 0.5f;
float alpha = 1.0f;
for (int j=0; j<height; j++) {
red = 1.0 / cryptoString[j];
for (int i=0; i<width; i++) {
int index = 4*(i+j*width);
data[index] =255*red;
data[++index]=255*green;
data[++index]=255*blue;
data[++index]=255*alpha;
}
}
// Create a CGImage with the pixel data
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, data, dataLength, NULL);
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGImageRef image = CGImageCreate(width, height, 8, 32, width * 4, colorspace, kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast,
provider, NULL, true, kCGRenderingIntentDefault);
//Clean up
CGColorSpaceRelease(colorspace);
CGDataProviderRelease(provider);
// Don't forget to free(data) when you are done with the CGImage
UIImage *img = [UIImage imageWithCGImage:image];
free(image);
free(data);
return img;
}
这是我用来创建图像的代码(它是 UIImage 上的一个类别)
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIImage *image = [UIImage imageEncryptingString:@"Hello World How are you doing?"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[self.view addSubview:imageView];
[self.view layoutSubviews];
}
这是我试图用来创建 ImageView 的代码。
这是我能够得到的调试器输出:
(lldb) po image.CGImage
error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=1, address=0x6353946e).
The process has been returned to the state before expression evaluation.
(lldb) p image.CGImage
error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=1, address=0x6353946e).
The process has been returned to the state before expression evaluation.
(lldb)
程序甚至不会在连接到调试器运行时崩溃,它只是继续突出显示行 UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
最佳答案
尝试在 CGImageRef 上调用 CFRelease(image)
而不是在 imageEncryptingString:
方法中调用 free
关于ios - 在 iOS 上创建图像并尝试将图像分配给 UIImageView 导致 EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21917234/