Created
January 20, 2015 06:33
-
-
Save ntnmrndn/045abc4875291a50018b to your computer and use it in GitHub Desktop.
A swift UIImage category to convert an image to black and white (truly, in shades of gray); preserving alpha as alpha.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// UIImage+convertToGreyScale.swift | |
// itooch | |
// | |
// Created by Antoine Marandon on 15/01/2015. | |
// Copyright (c) 2015 eduPad. All rights reserved. | |
// | |
import Foundation | |
extension UIImage { | |
private func convertToGrayScaleNoAlpha() -> CGImageRef { | |
let colorSpace = CGColorSpaceCreateDeviceGray(); | |
let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.None.rawValue) | |
let context = CGBitmapContextCreate(nil, UInt(size.width), UInt(size.height), 8, 0, colorSpace, bitmapInfo) | |
CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), self.CGImage) | |
return CGBitmapContextCreateImage(context) | |
} | |
/** | |
Return a new image in shades of gray + alpha | |
*/ | |
func convertToGrayScale() -> UIImage { | |
let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.Only.rawValue) | |
let context = CGBitmapContextCreate(nil, UInt(size.width), UInt(size.height), 8, 0, nil, bitmapInfo) | |
CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), self.CGImage); | |
let mask = CGBitmapContextCreateImage(context) | |
return UIImage(CGImage: CGImageCreateWithMask(convertToGrayScaleNoAlpha(), mask), scale: scale, orientation:imageOrientation)! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that iOS/macOS do not support gray scale with alpha (you have to use a RGB image with all 3 set to the same value + alpha to get this affect). In Swift 3 the function (not extension) to get gray scale is: