2016-03-21 18 views
1

Görüntüleri gri tonlamaya dönüştürmek için kullanıyorum kod budur. Ben siyah arka planlar görmek istemiyoruz enter image description hereenter image description hereResmi gri tonlamaya dönüştürür alfa

:

func convertToGrayScale(image: UIImage) -> UIImage 
{ 
    let imageRect:CGRect = CGRectMake(0, 0, image.size.width, image.size.height) 
    let colorSpace = CGColorSpaceCreateDeviceGray() 
    let width = image.size.width 
    let height = image.size.height 
    let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.None.rawValue) 
    let context = CGBitmapContextCreate(nil, Int(width), Int(height), 8, 0, colorSpace, bitmapInfo.rawValue) 
    CGContextDrawImage(context, imageRect, image.CGImage) 
    let imageRef = CGBitmapContextCreateImage(context) 
    let newImage = UIImage(CGImage: imageRef!) 
    return newImage 
} 

Bu

sonucudur. Bunu nasıl düzeltebilirim?

Düzenleme: Bunu, bu kodla yapmayı denedim, işe yarıyor, ancak artık resimlerin yüklenmesi 3 saniye sürüyor.

func convertToGrayScale(image: UIImage) -> UIImage { 

    let cgImage = image.CGImage! 

    let beginImage = CIImage(CGImage: cgImage) 
    let filter = CIFilter(name: "CIColorControls")! 
    filter.setValue(beginImage, forKey: kCIInputImageKey) 
    filter.setValue(0, forKey: kCIInputSaturationKey) 
    return UIImage(CIImage: filter.outputImage!) 
} 

cevap

1

Bu işlev sorunumu çözdü. Görüntüleri gri tonlamaya dönüştürmez, ancak bilinmeyen tarifler için siyah yapabildiğim, bilinen için bilinen yarı & için koyu gri.

func createTintedImageFromImage(originalImage: UIImage, desiredColor: UIColor) -> UIImage { 
    let imageSize: CGSize = originalImage.size 
    let imageScale: CGFloat = originalImage.scale 
    let contextBounds: CGRect = CGRectMake(0, 0, imageSize.width, imageSize.height) 

    UIGraphicsBeginImageContextWithOptions(imageSize, false, imageScale) 
    UIColor.blackColor().setFill() 
    UIRectFill(contextBounds) 
    originalImage.drawAtPoint(CGPointZero) 
    let imageOverBlack: UIImage = UIGraphicsGetImageFromCurrentImageContext() 
    desiredColor.setFill() 
    UIRectFill(contextBounds) 

    imageOverBlack.drawAtPoint(CGPointZero, blendMode: .Multiply, alpha: 1) 
    originalImage.drawAtPoint(CGPointZero, blendMode: .DestinationIn, alpha: 1) 

    let finalImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext() 
    return finalImage 
} 

enter image description here

İlgili konular