简体   繁体   中英

iPhone : How to change color of particular pixel of a UIImage?

I have a UIImage, I want to change colour of its particular pixel, say 224 x 200th pixel. How can I do this? Is it even possible to do? Thanks in advance.

After searching a lot for a complete day I got the exact solution, though I found many but none of them worked. Here is what I have got, it works flawlessly -:

// 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];

}

CGContextRef does all of this. You can do all sorts of magic with this.

Here are some slides that go over basic usage.

It is possible with core graphics. The link has code to convert your image to grey scale. You can modify it for your need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM