2014-12-04 66 views
0

我有一个简单的UIImageView,带有某人的图像。现在我想根据它们的位置或一些帧值来改变一些像素的颜色。如何做到这一点?更改UIImage中某些特定像素的颜色

任何帮助......

+0

添加视图,在您的ImageView – 2014-12-04 05:22:18

+0

添加另一种观点认为不给我理所当然的样子,我想这种变化看起来更自然的原始图像。 – 2014-12-04 05:23:16

+0

使用另一个imagview而不是视图 – 2014-12-04 05:24:21

回答

0

对于长期实现The你应该看看核心图像框架tutorial。 对于一次性案例,你可以参考已有的答案iPhone : How to change color of particular pixel of a UIImage? 我发现了很好的非ARC解决方案,它可以改变整个帧内的图片颜色,但是你可以尝试采用它来仅应用于某个像素:

- (void) grayscale:(UIImage*) image { 
    CGContextRef ctx; 
    CGImageRef imageRef = [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); 

    // Now your rawData contains the image data in the RGBA8888 pixel format. 
    int byteIndex = (bytesPerRow * 0) + 0 * bytesPerPixel; 
    for (int ii = 0 ; ii < width * height ; ++ii) 
    { 
     // Get color values to construct a UIColor 
      CGFloat red = (rawData[byteIndex]  * 1.0)/255.0; 
     CGFloat green = (rawData[byteIndex + 1] * 1.0)/255.0; 
     CGFloat blue = (rawData[byteIndex + 2] * 1.0)/255.0; 
     CGFloat alpha = (rawData[byteIndex + 3] * 1.0)/255.0; 

     rawData[byteIndex] = (char) (red); 
     rawData[byteIndex+1] = (char) (green); 
     rawData[byteIndex+2] = (char) (blue); 

     byteIndex += 4; 
    } 

    ctx = CGBitmapContextCreate(rawData, 
           CGImageGetWidth(imageRef), 
           CGImageGetHeight(imageRef), 
           8, 
           CGImageGetBytesPerRow(imageRef), 
           CGImageGetColorSpace(imageRef), 
           kCGImageAlphaPremultipliedLast); 

    imageRef = CGBitmapContextCreateImage (ctx); 
    UIImage* rawImage = [UIImage imageWithCGImage:imageRef]; 

    CGContextRelease(ctx); 

    self.workingImage = rawImage; 
    [self.imageView setImage:self.workingImage]; 

    free(rawData); 

} 

来源:不同颜色的http://brandontreb.com/image-manipulation-retrieving-and-updating-pixel-values-for-a-uiimage

+0

第二个链接的代码有错误,没有编译.. – 2014-12-04 05:59:20

+0

添加了一个更多的解决方案,可能被采纳为您的需求。 – 2014-12-04 10:57:39