UIImage のすべてのピクセルの色を変更したい。このコードは、単一のポイントの色を正常に変更しますが、画像全体のループで実行すると、画像が消えます。最初にピクセルの色の値を読み取り、次にこのピクセルの色に変更を適用します。また、ループは i の 0 値に対してのみ実行されます。以下はコードです
UIImage *grayImage=[UIImage imageWithCGImage:source.CGImage];
for(int i=0;i<imageToTest.frame.size.width;i++){
for(int j=0;j<imageToTest.frame.size.height;j++){
NSLog(@"%d",i);
CGPoint point=CGPointMake((CGFloat) i,(CGFloat) j);
if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, source.size.width, source.size.height), point)) {
return nil;
}
NSInteger pointX = trunc(point.x);
NSInteger pointY = trunc(point.y);
CGImageRef cgImage = source.CGImage;
NSUInteger width = CGImageGetWidth(cgImage);
NSUInteger height = CGImageGetHeight(cgImage);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
int bytesPerPixel = 4;
int bytesPerRow = bytesPerPixel * 1;
NSUInteger bitsPerComponent = 8;
unsigned char pixelData[4] = { 0, 0, 0, 0 };
CGContextRef context = CGBitmapContextCreate(pixelData,
1,
1,
bitsPerComponent,
bytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextSetBlendMode(context, kCGBlendModeCopy);
// Draw the pixel we are interested in onto the bitmap context
CGContextTranslateCTM(context, -pointX, -pointY);
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height), cgImage);
CGContextRelease(context);
// Convert color values [0..255] to floats [0.0..1.0]
CGFloat red = (CGFloat)pixelData[0] / 255.0f;
CGFloat green = (CGFloat)pixelData[1] / 255.0f;
CGFloat blue = (CGFloat)pixelData[2] / 255.0f;
CGFloat alpha = (CGFloat)pixelData[3] / 255.0f;
UIColor *currentPixelColor;
CGFloat Answer=sliderValue/10;
red=red*Answer;
green=green*Answer;
blue=blue*Answer;
alpha=alpha*Answer;
currentPixelColor=[UIColor colorWithRed:red green:green blue:blue alpha:alpha];
int width2 = source.size.width;
int height2 = source.size.height;
CGColorSpaceRef colorSpace2 = CGColorSpaceCreateDeviceRGB();
CGContextRef context2 = CGBitmapContextCreate (nil,
width2,
height2,
8,
0,
colorSpace2,
kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorSpace2);
if (context2 == NULL) {
return nil;
}
CGContextDrawImage(context2,
CGRectMake(0, 0, width2, height2), grayImage.CGImage);
CGContextSetFillColorWithColor(context2, currentPixelColor.CGColor);
CGContextFillRect(context2, CGRectMake(point.x, point.y, 1, 1));
grayImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context2)];
CGContextRelease(context2);
}
}
return grayImage;
}