Skip to content

Instantly share code, notes, and snippets.

@armstrongnate
Last active December 2, 2015 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save armstrongnate/4b6612f9a7989b7f5150 to your computer and use it in GitHub Desktop.
Save armstrongnate/4b6612f9a7989b7f5150 to your computer and use it in GitHub Desktop.
//
// UIImage+Blurs.swift
//
// Created by Nate Armstrong on 12/2/15.
// Copyright © 2015 Nate Armstrong. All rights reserved.
//
//
// Compression uses RBResizer: https://gist.github.com/hcatlin/180e81cd961573e3c54d
import Foundation
extension UIImage {
//
// returns a copy of self with a blur applied at the given rect
//
func blr_imageWithBlurInRect(rect: CGRect, blurRadius: CGFloat) -> UIImage? {
// crop
guard var copy = blr_imageByCroppingInRect(rect) else {
return nil
}
// blur
copy = UIImageEffects.imageByApplyingBlurToImage(copy, withRadius: blurRadius, tintColor: nil, saturationDeltaFactor: 1, maskImage: nil)
// merge
copy = blr_imageByMergingImage(copy, atPoint: rect.origin)
return copy
}
//
// returns a copy of self cropped at the given rect
//
func blr_imageByCroppingInRect(rect: CGRect) -> UIImage? {
guard let imageRef = CGImageCreateWithImageInRect(self.CGImage, rect) else {
return nil
}
return UIImage(CGImage: imageRef)
}
//
// returns a copy of self merged with the given image at the given rect
//
func blr_imageByMergingImage(image: UIImage, atPoint point: CGPoint) -> UIImage {
UIGraphicsBeginImageContext(size)
drawAtPoint(CGPointZero)
image.drawAtPoint(point)
let merged = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return merged
}
//
// returns a copy of self resized and compressed as NSData
//
func blr_compressForWeb() -> NSData {
let resized = RBResizeImage(self, targetSize: CGSize(width: 640, height: 1136))
return UIImageJPEGRepresentation(resized, 0.5)!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment