Created
February 17, 2016 09:37
-
-
Save omaarr90/e39ac97e705f0af622db to your computer and use it in GitHub Desktop.
UIImage extensions in swift, If you land on this gist by any chance. feel free to use it :)
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
// | |
// UIImageView+Omar.swift | |
// ......... | |
// | |
// Created by Omar Alshammari on 12/20/15. | |
// Copyright © 2015 ___OALSHAMMARI___. All rights reserved. | |
// | |
/* | |
This enum is to help referencing Assets ID. | |
*/ | |
enum AssetCatalogIdentifier: String { | |
case PlaceHolder = "placeHolder" | |
} | |
/* | |
Possible Bar code types. | |
*/ | |
enum BarCodeType: String { | |
case Aztec = "CIAztecCodeGenerator" | |
case Code128 = "CICode128BarcodeGenerator" | |
case PDF417Barcode = "CIPDF417BarcodeGenerator" | |
case QR = "CIQRCodeGenerator" | |
} | |
extension UIImage { | |
/* | |
Creates a a barcode as an image from the string provided. | |
*/ | |
convenience init(barCodeString: String, type: BarCodeType) { | |
let data = barCodeString.dataUsingEncoding(NSASCIIStringEncoding) | |
let filter = CIFilter(name: type.rawValue) | |
filter?.setValue(data, forKey: "inputMessage") | |
self.init(CIImage: (filter?.outputImage)!) | |
} | |
/* | |
initialize an image from assetID Enum. | |
*/ | |
convenience init?(assetID: AssetCatalogIdentifier) { | |
self.init(named: assetID.rawValue) | |
} | |
/* | |
returns a UIImage with corner radius of 20.0 | |
*/ | |
func roundCournerImage() -> UIImage { | |
let canvasRect = CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height) | |
let path = UIBezierPath(roundedRect: canvasRect, cornerRadius: 20.0) | |
return self.maskedImageWithPath(path) | |
} | |
/* | |
returns a circular image. e.g for profiles | |
*/ | |
func circularImage() -> UIImage { | |
let canvasRect = CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height) | |
let path = UIBezierPath(ovalInRect: canvasRect) | |
return self.maskedImageWithPath(path) | |
} | |
/* | |
returns a masked image based on the path provided. | |
*/ | |
func maskedImageWithPath(path: UIBezierPath) -> UIImage { | |
let size = CGSize(width: self.size.width, height: self.size.height) | |
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.mainScreen().scale) | |
let canvasRect = CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height) | |
path.addClip() | |
self.drawInRect(canvasRect) | |
let outputImage = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
return outputImage | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment