Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Love Wins in Swift
//
// loveWins(): a simple function that accepts a UIImage and
// returns the same image blended with the rainbow flag
// of the LGBT pride movement.
//
// This is released for pedagogical reasons (I've tried to make
// the code as easy to follow as possible!) but you're welcome
// to use it for any purpose – consider the code yours.
//
// If you're using Xcode 7 / Swift 2, you need to make a tiny
// change, so please read the comment on line 56.
//
// Questions?
// Twitter: @twostraws
// Web: www.hackingwithswift.com
//
func loveWins(img: UIImage) -> UIImage {
// create a CGRect representing the full size of our input iamge
let flagRect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)
// figure out the height of one flag section (there are six)
let sectionHeight = img.size.height / 6
// set up the colors for our flag – these are based on my trial and error
// based on what looks good blended with white using Core Graphics blend modes
let red = UIColor(red: 1, green: 0.5, blue: 0.5, alpha: 0.8).CGColor
let orange = UIColor(red: 1, green: 0.7, blue: 0.35, alpha: 0.8).CGColor
let yellow = UIColor(red: 1, green: 0.85, blue: 0.1, alpha: 0.65).CGColor
let green = UIColor(red: 0, green: 0.7, blue: 0.2, alpha: 0.5).CGColor
let blue = UIColor(red: 0, green: 0.35, blue: 0.7, alpha: 0.5).CGColor
let purple = UIColor(red: 0.3, green: 0, blue: 0.5, alpha: 0.6).CGColor
let colors = [red, orange, yellow, green, blue, purple]
// set up our drawing context
UIGraphicsBeginImageContextWithOptions(img.size, true, 0)
let context = UIGraphicsGetCurrentContext()
// fill the background with white so that translucent colors get lighter
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
CGContextFillRect(context, flagRect)
// loop through all six colors
for i in 0 ..< 6 {
let color = colors[i]
// figure out the rect for this flag section
let rect = CGRect(x: 0, y: CGFloat(i) * sectionHeight, width: flagRect.width, height: sectionHeight)
// draw it onto the context at the right place
CGContextSetFillColorWithColor(context, color)
CGContextFillRect(context, rect)
}
// now draw our input image over using Luminosity mode, with a little bit of alpha to make it fainter
// IF YOU ARE USING SWIFT 2: Change "kCGBlendModeLuminosity" to ".Luminosity" and you're done
img.drawInRect(flagRect, blendMode: kCGBlendModeLuminosity, alpha: 0.6)
// grab the finished image and return it
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.