2013-05-09 48 views

Trả lời

8

Sau khi tìm kiếm rất nhiều cho một ngày hoàn chỉnh, tôi đã nhận được giải pháp chính xác, mặc dù tôi đã tìm thấy nhiều nhưng không có ai trong số họ làm việc. Dưới đây là những gì tôi đã có, nó hoạt động hoàn hảo -:

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

}

+6

giá trị của pixelCountForCalculatingAvgColor và avgRGBsOfPixel là gì? Nó không biên dịch .. –

+0

Xin chào, tôi không hiểu ở đâu hoặc tại dòng nào chúng tôi đang thực sự thiết lập/thay đổi màu pixel? Vui lòng giải thích –

+1

@Vipul J bạn có thể xóa những thứ không xác định này hoặc giá trị pixelCountForCalculatingAvgColor và giá trị mảng của avgRGBsOfPixel không? –

0

Có thể có đồ họa lõi. link có mã để chuyển đổi hình ảnh của bạn thành thang màu xám. Bạn có thể sửa đổi nó cho nhu cầu của bạn.

0

CGContextRef thực hiện tất cả điều này. Bạn có thể làm tất cả các loại phép thuật với điều này.

Here are some slides vượt quá mức sử dụng cơ bản.

Các vấn đề liên quan