首先抱歉我的英语。 我在做iOS应用程序。我决定使用逐像素处理图像。需要创建困难的“刷子”工具。我使用this算法。
我的代码:
ViewController.h
#import <UIKit/UIKit.h>
@interface MVRViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) UIImage *image;
@end
ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.image = [UIImage imageNamed:@"grid_750x450.png"];
self.imageView.image = self.image;
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
NSSet *allTouches = [event allTouches];
UITouch *touch = [[allTouches allObjects] objectAtIndex:0];
CGPoint imageViewPoint = [touch locationInView:self.imageView];
if ((imageViewPoint.x < self.imageView.frame.size.width) && (self.imageViewPoint.y < imageView.frame.size.height)) {
// Create image buffer
CGContextRef ctx;
CGImageRef imageRef = [self.image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
// Do something with image buffer
int X = imageViewPoint.x;
int Y = imageViewPoint.y;
for (int X1=X-14; ((X1<X+14) && (X1<width)); X1++) {
for (int Y1=Y-14; ((Y1<Y+14) && (Y1<height)); Y1++) {
int byteIndex = (bytesPerRow * Y1) + X1 * bytesPerPixel;
rawData[byteIndex]=255; // new red
rawData[byteIndex+1]=0; // new green
rawData[byteIndex+2]=0; // new blue
}
}
// Save image buffer to UIImage
ctx = CGBitmapContextCreate(rawData,
CGImageGetWidth( imageRef ),
CGImageGetHeight( imageRef ),
8,
CGImageGetBytesPerRow( imageRef ),
CGImageGetColorSpace( imageRef ),
kCGImageAlphaPremultipliedLast );
imageRef = CGBitmapContextCreateImage (ctx);
UIImage* rawImage = [UIImage imageWithCGImage:imageRef];
CGContextRelease(ctx);
self.image = rawImage;
self.imageView.image = self.image;
CGImageRelease(imageRef);
free(rawData);
}
}
申请是有效的。但...
我的问题:应用程序因内存不足错误(在设备上)而崩溃。
从仪器(分配配置文件)我看到unsigned char *rawData = malloc(height * width * 4);
从未发布过,free(rawData)
功能不起作用,我猜。在模拟器内存增长到“无限”(3Gb ......)。
我哪里错了?谢谢!