[英]iPhone : How to change color of particular pixel of a UIImage?
我有一個UIImage,我想改變它的特定像素的顏色,比如224 x 200像素。 我怎樣才能做到這一點? 它甚至可以嗎? 提前致謝。
經過一整天的搜索,我得到了確切的解決方案,雖然我找到了很多,但沒有一個工作。 這是我所擁有的,它完美無缺 - :
// 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完成了所有這些。 你可以用這種方法做各種各樣的魔術。
核心圖形是可能的。 該鏈接具有將圖像轉換為灰度的代碼。 您可以根據需要進行修改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.