7

我有一个 UIImage,我想改变它特定像素的颜色,比如 224 x 200 像素。我怎样才能做到这一点?甚至有可能做到吗?提前致谢。

4

3 回答 3

9

在搜索了整整一天之后,我得到了确切的解决方案,虽然我发现了很多但没有一个有效。这是我所得到的,它完美无缺-:

// This method creates an image by changing individual pixels of an image. Color of pixel has been taken from an array of colours('avgRGBsOfPixel')
-(void)createTexture{

self.sampleImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"whitebg.jpg"]];
CGRect imageRect = CGRectMake(0, 0, self.sampleImage.image.size.width, self.sampleImage.image.size.height);

UIGraphicsBeginImageContext(sampleImage.image.size);
CGContextRef context = UIGraphicsGetCurrentContext();

//Save current status of graphics context
CGContextSaveGState(context);
CGContextDrawImage(context, imageRect, sampleImage.image.CGImage);
//    And then just draw a point on it wherever you want like this:

//    CGContextFillRect(context, CGRectMake(x,y,1,1));
//Fix error according to @gsempe's comment
int pixelCount =0;
for(int i = 0 ; i<sampleImage.image.size.width ; i++){
    for(int j = 0 ; j<sampleImage.image.size.height ; j++){
        pixelCount++;
        int index = pixelCount/pixelCountForCalculatingAvgColor;
        //            NSLog(@"Index : %d", index);
        if(index >= [avgRGBsOfPixel count]){
            index = [avgRGBsOfPixel count] -1;
            NSLog(@"Bad Index");
        }
        //            if(pixelCount >9999){
        //                pixelCount = 9999;
        //                NSLog(@"Bad Index");
        //            }
        UIColor *color = [avgRGBsOfPixel objectAtIndex:index];
        float red ,green, blue ,alpha ;
        [color getRed:&red green:&green blue:&blue alpha:&alpha];
        CGContextSetRGBFillColor(context, red , green, blue , 1);
        CGContextFillRect(context, CGRectMake(i,j,1,1));
    }
}

//    Then just save it to UIImage again:

CGContextRestoreGState(context);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
[self.iv setImage:img];

}

于 2013-05-12T08:05:51.803 回答
1

CGContextRef完成了所有这些工作。你可以用这个做各种魔法。

以下是一些介绍基本用法的幻灯片。

于 2013-05-09T12:56:20.347 回答
0

核心图形是可能的。该链接包含将图像转换为灰度的代码。您可以根据需要对其进行修改。

于 2013-05-09T12:48:56.087 回答