天天看點

iPhone How-to:圖檔的灰階處理

原文位址:http://bj007.blog.51cto.com/1701577/541525

表示點選無效或者使用者離線的情況下通常會使用一些灰階圖檔。在iPhone中如何将普通圖檔轉換成相應的灰階圖像呢?下面這段代碼給出了答案。

  1. UIImage *grayImage(UIImage *source)  
  2. {  
  3.     int width = source.size.width;  
  4.     int height = source.size.height;  
  5.     CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();  
  6.     CGContextRef context = CGBitmapContextCreate (nil,  
  7.                          width,  
  8.                          height,  
  9.                          8,      // bits per component  
  10.                          0,  
  11.                          colorSpace,  
  12.                          kCGImageAlphaNone);  
  13.     CGColorSpaceRelease(colorSpace);  
  14.     if (context == NULL) {  
  15.         return nil;  
  16.     }  
  17.     CGContextDrawImage(context,  
  18.         CGRectMake(0, 0, width, height), source.CGImage);  
  19.     UIImage *grayImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)];  
  20.     CGContextRelease(context);  
  21.     return grayImage;  

 其中,CGColorSpaceCreateDeviceGray會建立一個裝置相關的灰階顔色空間的引用。