2012-07-09 16 views
7

Sto impostando UImageViews all'interno delle celle di una tabella utilizzando setImageWithUrl dalla libreria AFNetworking, ma ho bisogno che le immagini siano in scala di grigi ... c'è un modo per farlo. Ho provato alcuni convertitori UIImage in scala di grigi, ma suppongo che non funzionino perché sto impostando qualcosa che non è ancora stato scaricato.Creazione di UIImageView grigio

+1

[Provare con un Core Image filtro come questo] [1] [1]: http://stackoverflow.com/questions/10030631/what-is-the-best-core- image-filter-to-produce-black-and-white-effetti –

risposta

14

provare questo metodo:

- (UIImage *)convertImageToGrayScale:(UIImage *)image 
{ 
    // Create image rectangle with current image width/height 
    CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height); 

    // Grayscale color space 
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray(); 

    // Create bitmap content with current image size and grayscale colorspace 
    CGContextRef context = CGBitmapContextCreate(nil, image.size.width, image.size.height, 8, 0, colorSpace, kCGImageAlphaNone); 

    // Draw image into current context, with specified rectangle 
    // using previously defined context (with grayscale colorspace) 
    CGContextDrawImage(context, imageRect, [image CGImage]); 

    // Create bitmap image info from pixel data in current context 
    CGImageRef imageRef = CGBitmapContextCreateImage(context); 

    // Create a new UIImage object 
    UIImage *newImage = [UIImage imageWithCGImage:imageRef]; 

    // Release colorspace, context and bitmap information 
    CGColorSpaceRelease(colorSpace); 
    CGContextRelease(context); 
    CFRelease(imageRef); 

    // Return the new grayscale image 
    return newImage; 
} 

ho trovato qui: http://mobiledevelopertips.com/graphics/convert-an-image-uiimage-to-grayscale.html

+1

Questo ha funzionato molto bene per me! Ho provato il filtro Core Image e le prestazioni erano scarse nella mia vista di raccolta. Usando questo metodo è molto veloce. ben fatto –

+1

Funziona solo se non si usa la trasparenza (l'alpha è impostato su Nessuno). –

1

invece di un UIImageView, sottoclasse di UIView, dargli

@property (strong, nonatomic) UIImage *image; 

con

@synthesize image = _image; 

Override il setter

-(void)setImage:(UIImage *)image{ 
    _image = [self makeImageBW:image]; 
    [self setNeedsDisplay]; 
} 

- (UIImage *)makeImageBW:(UIImage *)source 
{ 
    CIImage *beginImage = source.CIImage; 
    CIImage *blackAndWhite = [CIFilter filterWithName:@"CIColorControls" keysAndValues:kCIInputImageKey, beginImage, @"inputBrightness", [NSNumber numberWithFloat:0.0], @"inputContrast", [NSNumber numberWithFloat:1.1], @"inputSaturation", [NSNumber numberWithFloat:0.0], nil].outputImage; 
    CIImage *output = [CIFilter filterWithName:@"CIExposureAdjust" keysAndValues:kCIInputImageKey, blackAndWhite, @"inputEV", [NSNumber numberWithFloat:0.7], nil].outputImage; 
    CIContext *context = [CIContext contextWithOptions:nil]; 
    CGImageRef ref = [context createCGImage:output fromRect:output.extent]; 
    UIImage *newImage = [UIImage imageWithCGImage:ref]; 
    CGImageRelease(cgiimage); 
    return newImage; 
} 

-(void)drawRect:(CGRect)rect{ 
    [_image drawInRect:rect]; 
} 

da qualche altra parte è possibile impostare l'immagine con il NSURLRequest:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^{ 
     NSData *data = [NSURLConnection sendSynchronousRequest:(NSURLRequest *) returningResponse:nil error:nil]; 
     if (data){ 
      UIImage *image = [UIImage imageWithData:data]; 
      if (image) dispatch_async(dispatch_get_main_queue(),^{ 
       [view setImage:image]; 
      }); 
     } 
}); 
+0

Penso che renderlo un UIView non mi permetterebbe di usare il metodo setImageWithUrl di AFNetworking ..? – cannyboy

+0

Non ho familiarità con AFNetworking, ho aggiunto il codice in modo che funzioni senza la libreria AF –

+0

personalmente lo aggiungerei come categoria su 'UIImage':' - [UIImage (Greyscale) grayscaleImage] '... allora tu non è necessario sottoclasse nulla. – nielsbot

3

ho preso il codice dall'esempio di @Jesse Gumpo, al di sopra, ma qui è come interfaccia.

@implementation UIImage (Greyscale) 

- (UIImage *)greyscaleImage 
{ 
    CIImage * beginImage = [ self CIImage ] ; 
    CIImage * evAdjustedCIImage = nil ; 
    { 
     CIFilter * filter = [ CIFilter filterWithName:@"CIColorControls" 
             keysAndValues:kCIInputImageKey, beginImage 
              , @"inputBrightness", @0.0 
              , @"inputContrast", @1.1 
              , @"inputSaturation", @0.0 
              , nil ] ; 
     evAdjustedCIImage = [ filter outputImage ] ; 
    } 

    CIImage * resultCIImage = nil ; 
    { 
     CIFilter * filter = [ CIFilter filterWithName:@"CIExposureAdjust" 
             keysAndValues:kCIInputImageKey, evAdjustedCIImage 
              , @"inputEV", @0.7 
              , nil ] ; 
     resultCIImage = [ filter outputImage ] ; 
    } 

    CIContext * context = [ CIContext contextWithOptions:nil ] ; 
    CGImageRef resultCGImage = [ context createCGImage:resultCIImage 
               fromRect:resultCIImage.extent ] ; 
    UIImage * result = [ UIImage imageWithCGImage:resultCGImage ] ; 
    CGImageRelease(resultCGImage) ; 

    return result; 
} 

@end 

Ora si può solo fare questo:

UIImage * downloadedImage = ... get from AFNetwork results ... ; 
downloadedImage = [ downloadedImage greyscaleImage ] ; 

... use 'downloadedImage' ... 
+0

Hai bisogno di passare il codice sorgente se viene chiamato su una UIImage? La chiamata di funzione inferiore sembra semplice, ma l'interfaccia sopra richiede un parametro di input, che sembra non necessario. Cosa succede se viene chiamato semplicemente - (UIImage *) greyscaleImage? – Cindeselia

+0

Sì, era un errore di battitura. Grazie. – nielsbot

1

Questo thread è un po 'vecchio, ma mi sono imbattuto sulla mia ricerca. In this post ho indicato 2 diversi metodi in Swift per creare un'immagine in scala di grigi che può essere visualizzata in un imageView considerando l'alfa e la scala dell'immagine.

import CoreImage 

extension UIImage 
{ 
    /// Applies grayscale with CIColorControls by settings saturation to 0.0. 
    /// - Parameter brightness: Default is 0.0. 
    /// - Parameter contrast: Default is 1.0. 
    /// - Returns: The grayscale image of self if available. 
    func grayscaleImage(brightness: Double = 0.0, contrast: Double = 1.0) -> UIImage? 
    { 
     if let ciImage = CoreImage.CIImage(image: self, options: nil) 
     { 
      let paramsColor: [String : AnyObject] = [ kCIInputBrightnessKey: NSNumber(double: brightness), 
                 kCIInputContrastKey: NSNumber(double: contrast), 
                 kCIInputSaturationKey: NSNumber(double: 0.0) ] 
      let grayscale = ciImage.imageByApplyingFilter("CIColorControls", withInputParameters: paramsColor) 

      let processedCGImage = CIContext().createCGImage(grayscale, fromRect: grayscale.extent) 
      return UIImage(CGImage: processedCGImage, scale: self.scale, orientation: self.imageOrientation) 
     } 
     return nil 
    } 

    /// Create a grayscale image with alpha channel. Is 5 times faster than grayscaleImage(). 
    /// - Returns: The grayscale image of self if available. 
    func convertToGrayScale() -> UIImage? 
    { 
     // Create image rectangle with current image width/height * scale 
     let pixelSize = CGSize(width: self.size.width * self.scale, height: self.size.height * self.scale) 
     let imageRect = CGRect(origin: CGPointZero, size: pixelSize) 
     // Grayscale color space 
     if let colorSpace: CGColorSpaceRef = CGColorSpaceCreateDeviceGray() 
     { 
      // Create bitmap content with current image size and grayscale colorspace 
      let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.None.rawValue) 
      if let context: CGContextRef = CGBitmapContextCreate(nil, Int(pixelSize.width), Int(pixelSize.height), 8, 0, colorSpace, bitmapInfo.rawValue) 
      { 
       // Draw image into current context, with specified rectangle 
       // using previously defined context (with grayscale colorspace) 
       CGContextDrawImage(context, imageRect, self.CGImage) 
       // Create bitmap image info from pixel data in current context 
       if let imageRef: CGImageRef = CGBitmapContextCreateImage(context) 
       { 
        let bitmapInfoAlphaOnly = CGBitmapInfo(rawValue: CGImageAlphaInfo.Only.rawValue) 
        if let contextAlpha = CGBitmapContextCreate(nil, Int(pixelSize.width), Int(pixelSize.height), 8, 0, nil, bitmapInfoAlphaOnly.rawValue) 
        { 
         CGContextDrawImage(contextAlpha, imageRect, self.CGImage) 
         if let mask: CGImageRef = CGBitmapContextCreateImage(contextAlpha) 
         { 
          // Create a new UIImage object 
          if let newCGImage = CGImageCreateWithMask(imageRef, mask) 
          { 
           // Return the new grayscale image 
           return UIImage(CGImage: newCGImage, scale: self.scale, orientation: self.imageOrientation) 
          } 
         } 
        } 
       } 
      } 

     } 
     // A required variable was unexpected nil 
     return nil 
    } 
} 
+0

Devi dettagliare il tuo post qui se vuoi che questa risposta rimanga su questo sito. – Martin

+0

@ Martin Ho copiato il codice di estensione per te. – FBente