Giter VIP home page Giter VIP logo

imagehelper's Introduction

ImageHelper

Version License Platform Carthage compatible

Image Extensions for Swift 3.0

Sample Project Screenshot

Usage

To run the example project, clone or download the repo, and run.

UIImageView Extension

Image from a URL

// Fetches an image from a URL. If caching is set, it will be cached by NSCache for future queries. The cached image is returned if available, otherise the placeholder is set. When the image is returned, the closure gets called.
func imageFromURL(url: String, placeholder: UIImage, fadeIn: Bool = true, closure: ((image: UIImage?)

UIImage Extension

Colors

// Creates an image from a solid color
UIImage(color:UIColor, size:CGSize)

// Creates an image from a gradient color
UIImage(gradientColors:[UIColor], size:CGSize)

// Applies a gradient overlay to an image
func applyGradientColors(gradientColors: [UIColor], blendMode: CGBlendMode) -> UIImage

// Creates an image from a radial gradient
UIImage(startColor: UIColor, endColor: UIColor, radialGradientCenter: CGPoint, radius:Float, size:CGSize)

Text

// Creates an image with a string of text
UIImage(text: String, font: UIFont, color: UIColor, backgroundColor: UIColor, size:CGSize, offset: CGPoint)

Screenshot

// Creates an image from a UIView
UIImage(fromView view: UIView)

Alpha and Padding

// Returns true if the image has an alpha layer
func hasAlpha() -> Bool

// Returns a copy(if needed) of the image with alpha layer
func applyAlpha() -> UIImage?

// Returns a copy of the image with a transparent border of the given size added around its edges
func applyPadding(padding: CGFloat) -> UIImage?

Crop and Resize

// Crops an image to a new rect
func crop(bounds: CGRect) -> UIImage?

// Crops an image to a centered square
func cropToSquare() -> UIImage? {

// Resizes an image
func resize(size:CGSize, contentMode: UIImageContentMode = .ScaleToFill) -> UIImage?

Circle and Rounded Corners

// Rounds corners of an image
func roundCorners(cornerRadius:CGFloat) -> UIImage?

// Rounds corners of an image with border
func roundCorners(cornerRadius:CGFloat, border:CGFloat, color:UIColor) -> UIImage?

// Rounds corners to a circle
func roundCornersToCircle() -> UIImage?

// Rounds corners to a circle with border
func roundCornersToCircle(border border:CGFloat, color:UIColor) -> UIImage?

Border

// Adds a border
func applyBorder(border:CGFloat, color:UIColor) -> UIImage?

Image Effects

// Applies a light blur effect to the image
func applyLightEffect() -> UIImage?
// Applies a extra light blur effect to the image
func applyExtraLightEffect() -> UIImage?
// Applies a dark blur effect to the image
func applyDarkEffect() -> UIImage?
// Applies a color tint to an image
func applyTintEffect(tintColor: UIColor) -> UIImage?
// Applies a blur to an image based on the specified radius, tint color saturation and mask image
func applyBlur(blurRadius:CGFloat, tintColor:UIColor?, saturationDeltaFactor:CGFloat, maskImage:UIImage? = nil) -> UIImage?

Screen Density

// To create an image that is Retina aware, use the screen scale as a multiplier for your size. You should also use this technique for padding or borders.
let width = 140 * UIScreen.mainScreen().scale
let height = 140 * UIScreen.mainScreen().scale
let image = UIImage(named: "myImage")?.resize(CGSize(width: width, height: height))

imagehelper's People

Contributors

diogowbrito avatar jallen avatar jedmund avatar maml avatar melvitax avatar nickvelloff avatar rokgregoric avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

imagehelper's Issues

Crashing while scrolling through a list of cached images, while offline

imageFromURL crashes when scrolling through a list of images while offline.
The images were previously loaded and caches.

I was able to trace the error to an explicit bang here:
if let image = UIImage(data: data!) {

After checking for data the app seemed to work ok.

I already submitted a PR that seems to fix the issue.

Crash on IOS 11

I have a UITableView which has list of users with their profile pic. I used image?.roundCornersToCircle() to round the image since the height and width of `UIImageView were not same.

But in IOS 11, it crashes in this method UIImage.applyAlpha() -> UIImage?.

Crashlytics suggests that let imageWithAlpha = UIImage(cgImage: (offscreenContext?.makeImage()!)!) line caused the crash.

I have attached the image which was creating this issue below. (The image is in white color)

01ltxi70aajdjesfoodnh3lawsmrimucocmrokvl

the method of roundCorners doesn't always work ...

Fetches an image from a URL ...

sometimes the roundCorners can work,but it doesn't ...

cell.portraitUIImageView.imageFromURL(portraitURL, placeholder: image, fadeIn: true) {
(image: UIImage?) in
if image != nil {
cell.portraitUIImageView.image = image?.roundCorners(cornerRadius: CGFloat(image!.size.width/2), border: CGFloat(2.0), color: UIColor.red)
}
}

Resizing doesn't work

print("Before resizing size", image?.size) let resizedImage = image?.resize(toSize: CGSize(width: 600, height: 600)) print("After resizing size", resizedImage?.size)
same size before and after resizing...

Swift 2 Support

Hello, do you consider to update this really good library to Swift 2?

Thanks in advance. :)

Patrik

Initializer error in XCode 6.1 GM seed

I'm having the following error with yesterdays GM 6.1 seed of XCode:
A non-failable initializer cannot delegate to failable initializer 'init(CGImage:)' written with 'init?'

I assume that the init(CGImage:) initializer was changed from auto-unwrapping optional (!) to optional (?).

Crop by Mask

Hello! Great job!

Could you add function for crop UIImage by mask like:

  • (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage

Images loaded from NSData that are cropped to a square are double sized on retina

Here is the new cropToSquare()

func cropToSquare() -> UIImage? {

    //properly handle image scale
    let size = CGSizeMake(self.size.width * self.scale, self.size.height * self.scale)

    let shortest = min(size.width, size.height)
    let left: CGFloat = size.width > shortest ? (size.width-shortest)/2 : 0
    let top: CGFloat = size.height > shortest ? (size.height-shortest)/2 : 0
    let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
    let insetRect = CGRectInset(rect, left, top)
    return crop(insetRect)
}

I have not done thorough testing, so I'm worried this may break something else, you have tests you can run?

resize error

print(UIImage(named: "tryPhoto")!.size)
print(UIImage(named: "tryPhoto")!.resize(toSize: CGSize(width: 200, height: 300))!.size)
print(UIImage(named: "tryPhoto")!.resize(toSize: CGSize(width: 300, height: 400), contentMode: UIImageContentMode.scaleAspectFill)!.size)
print(UIImage(named: "tryPhoto")!.resize(toSize: CGSize(width: 400, height: 500), contentMode: UIImageContentMode.scaleToFill)!.size)
print(UIImage(named: "tryPhoto")!.resize(toSize: CGSize(width: 500, height: 600), contentMode: UIImageContentMode.scaleAspectFit)!.size)

return

(750.0, 905.0)
(750.0, 905.0)
(750.0, 905.0)
(750.0, 905.0)
(750.0, 905.0)

Apply a gradient to a UIImage seems broken

When applying this gradient to UIImages:

image.apply(gradientColors: [UIColor.yellow, UIColor.red], locations: [1.0, 0.0])

I would expect the whole image to be covered by the gradient since the colors are completely opaque.

However, it does sometimes seem to apply a strange blend mode, although the blend mode is left to the default value (CGBlendMode.normal).

See on the following example: the gradient is wrong on the 1st image, but correct on the 2nd image.

screenshot 2016-10-10 16 40 23

Here is a second example with the following gradient:

image.apply(gradientColors: [UIColor.black, UIColor.black], locations: [1, 0])

The 1st image is correct but the 2nd seems to be a negative.

screenshot 2016-10-10 16 48 04

I am using ImageHelper.swift and ImageVIewExtension.swift from master (24581b1)

Rounded border line is double wide when the image has transparent color?

Hi,

I'm using your library to crop images with 2 px white border and for the exactly same parameters (same image size, border color, border width, image scale) I'm getting too wide border line for some images. When I tried to debug the "applyBorder:" method I found out that even the "rect" and "inset" vars are the same.

My code is something here:

resultImage = resultImage.resize(CGSizeMake(100, 100), contentMode: UIImageContentMode.ScaleAspectFill)!
resultImage = resultImage.roundCornersToCircle(border: 2, color: UIColor.whiteColor())!

Any ideas?

[Feature Suggestion/Help For Others]Making a roundedimageFromURL method

I am sure lots of people will want to make a rounded image from a url for social apps etc I thought I would share below to help others.

If this is a good candidate for the library- happy to do a pull request. Maybe we can extend the image method to allow the user to customize the image shape that is cached to support other shapes.

Thanks for the wonderful library. Appreciate your efforts.

extension UIImageView {
 	
 	// Extending UIImageHelper with new handler for Round Images
 	/**
 	Loads an image and makes it into a circle from a URL. If cached, the cached image is returned. Otherwise, a place holder is used until the image from web is returned by the closure.
 	
 	- Parameter url: The image URL.
 	- Parameter placeholder: The placeholder image.
 	- Parameter fadeIn: Weather the mage should fade in.
 	- Parameter closure: Returns the image from the web the first time is fetched.
 	
 	- Returns A new image
 	*/
 	func roundedimageFromURL(_ url: String, placeholder: UIImage, fadeIn: Bool = true, shouldCacheImage: Bool = true, closure: ((_ image: UIImage?) -> ())?)
 	{
 		self.image = UIImage.roundImage(fromURL: url, placeholder: placeholder, shouldCacheImage: shouldCacheImage) {
 			(image: UIImage?) in
 			if image == nil {
 				return
 			}
 			self.image = image
 			if fadeIn {
 				let transition = CATransition()
 				transition.duration = 0.5
 				transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
 				transition.type = kCATransitionFade
 				self.layer.add(transition, forKey: nil)
 			}
 			closure?(self.image)
 		}
 	}
 	
 	
 
 }
 extension UIImage {
 	class func roundImage(fromURL url: String, placeholder: UIImage, shouldCacheImage: Bool = true, closure: @escaping (_ image: UIImage?) -> ()) -> UIImage? {
 		// From Cache
 		let urlKey = "round_\(url)"
 		if shouldCacheImage {
 			
 			if let image = UIImage.shared.object(forKey: urlKey as AnyObject) as? UIImage {
 				closure(nil)
 				return image
 			}
 		}
 		// Fetch Image
 		let session = URLSession(configuration: URLSessionConfiguration.default)
 		if let nsURL = URL(string: url) {
 			session.dataTask(with: nsURL, completionHandler: { (data, response, error) -> Void in
 				if (error != nil) {
 					DispatchQueue.main.async {
 						closure(nil)
 					}
 				}
 				if let data = data, let image = UIImage(data: data) {
 					if let roundImage = image.roundCornersToCircle() {
 					if shouldCacheImage {
 						UIImage.shared.setObject(roundImage, forKey: urlKey as AnyObject)
 					}
 					DispatchQueue.main.async {
 						closure(roundImage)
 					}
 					}
 				}
 				session.finishTasksAndInvalidate()
 			}).resume()
 		}
 		return placeholder
 	}
 
 }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.