Skip to content

Commit

Permalink
Fixed roundCorners and image with text. Updated sample code and read …
Browse files Browse the repository at this point in the history
…me file with screen density sample code.
  • Loading branch information
melvitax committed Dec 18, 2015
1 parent 7426fb1 commit 85e58b9
Show file tree
Hide file tree
Showing 9 changed files with 89 additions and 92 deletions.
2 changes: 1 addition & 1 deletion AFImageHelper.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

Pod::Spec.new do |s|
s.name = "AFImageHelper"
s.version = "3.0.1"
s.version = "3.0.2"
s.summary = "Image Extensions for Swift 2.0"
s.description = <<-DESC
A collection of extensions for handling image creation from colors and gradients; Manipulating by cropping and scaling; Background fetching from the web with support for caching.
Expand Down
Binary file not shown.
Binary file not shown.
132 changes: 66 additions & 66 deletions AFImageHelper/AFImageExtension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// AFImageExtension.swift
//
// AFImageHelper
// Version 3.0.1
// Version 3.0.2
//
// Created by Melvin Rivera on 7/5/14.
// Copyright (c) 2014 All Forces. All rights reserved.
Expand All @@ -22,8 +22,8 @@ public enum UIImageContentMode {
public extension UIImage {

/**
A singleton shared NSURL cache used for images from URL
*/
A singleton shared NSURL cache used for images from URL
*/
private class func sharedCache() -> NSCache!
{
struct StaticSharedCache {
Expand Down Expand Up @@ -78,13 +78,13 @@ public extension UIImage {
}

/**
Applies gradient color overlay to an image.
- Parameter gradientColors: An array of colors to use for the gradient.
- Parameter blendMode: The blending type to use.
- Returns A new image
*/
Applies gradient color overlay to an image.
- Parameter gradientColors: An array of colors to use for the gradient.
- Parameter blendMode: The blending type to use.
- Returns A new image
*/
func applyGradientColors(gradientColors: [UIColor], blendMode: CGBlendMode = CGBlendMode.Normal) -> UIImage
{
UIGraphicsBeginImageContextWithOptions(size, false, scale)
Expand Down Expand Up @@ -121,15 +121,15 @@ public extension UIImage {
*/
convenience init?(text: String, font: UIFont = UIFont.systemFontOfSize(18), color: UIColor = UIColor.whiteColor(), backgroundColor: UIColor = UIColor.grayColor(), size:CGSize = CGSizeMake(100, 100), offset: CGPoint = CGPoint(x: 0, y: 0))
{
let label = UILabel(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
label.font = font
label.text = text
label.textColor = color
label.textAlignment = .Center
label.backgroundColor = backgroundColor
let image = UIImage(fromView: label)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, backgroundColor.CGColor)
CGContextFillRect(context, CGRect(origin: CGPoint(x: 0, y: 0), size: size))
let style = NSMutableParagraphStyle()
style.alignment = .Center
let attr = [NSFontAttributeName:font, NSForegroundColorAttributeName:color, NSParagraphStyleAttributeName:style]
let rect = CGRect(x: offset.x, y: offset.y, width: size.width, height: size.height)
text.drawInRect(rect, withAttributes: attr)
image?.drawInRect(CGRect(x: 0, y: 0, width: size.width, height: size.height))
self.init(CGImage:UIGraphicsGetImageFromCurrentImageContext().CGImage!)
UIGraphicsEndImageContext()
}
Expand Down Expand Up @@ -209,8 +209,8 @@ public extension UIImage {
}

/**
Returns a copy of the given image, adding an alpha channel if it doesn't already have one.
*/
Returns a copy of the given image, adding an alpha channel if it doesn't already have one.
*/
func applyAlpha() -> UIImage?
{
if hasAlpha() {
Expand All @@ -233,12 +233,12 @@ public extension UIImage {
}

/**
Returns a copy of the image with a transparent border of the given size added around its edges. i.e. For rotating an image without getting jagged edges.
- Parameter padding: The padding amount.
- Returns A new image.
*/
Returns a copy of the image with a transparent border of the given size added around its edges. i.e. For rotating an image without getting jagged edges.
- Parameter padding: The padding amount.
- Returns A new image.
*/
func applyPadding(padding: CGFloat) -> UIImage?
{
// If the image does not have an alpha layer, add one
Expand All @@ -262,15 +262,15 @@ public extension UIImage {
let transparentImage = UIImage(CGImage: CGImageCreateWithMask(CGBitmapContextCreateImage(context), imageRefWithPadding(padding, size: rect.size))!)
return transparentImage
}

/**
Creates a mask that makes the outer edges transparent and everything else opaque. The size must include the entire mask (opaque part + transparent border).
- Parameter padding: The padding amount.
- Parameter size: The size of the image.

- Returns A Core Graphics Image Ref
*/
/**
Creates a mask that makes the outer edges transparent and everything else opaque. The size must include the entire mask (opaque part + transparent border).
- Parameter padding: The padding amount.
- Parameter size: The size of the image.
- Returns A Core Graphics Image Ref
*/
private func imageRefWithPadding(padding: CGFloat, size:CGSize) -> CGImageRef
{
// Build a context that's the same dimensions as the new size
Expand All @@ -288,7 +288,7 @@ public extension UIImage {
return maskImageRef!
}


// MARK: Crop

/**
Expand All @@ -301,7 +301,7 @@ public extension UIImage {
func crop(bounds: CGRect) -> UIImage?
{
return UIImage(CGImage: CGImageCreateWithImageInRect(self.CGImage, bounds)!,
scale: 0.0, orientation: self.imageOrientation)
scale: 0.0, orientation: self.imageOrientation)
}

func cropToSquare() -> UIImage? {
Expand Down Expand Up @@ -331,15 +331,15 @@ public extension UIImage {
var ratio: CGFloat!

switch contentMode {
case .ScaleToFill:
ratio = 1
case .ScaleAspectFill:
ratio = max(horizontalRatio, verticalRatio)
case .ScaleAspectFit:
ratio = min(horizontalRatio, verticalRatio)
case .ScaleToFill:
ratio = 1
case .ScaleAspectFill:
ratio = max(horizontalRatio, verticalRatio)
case .ScaleAspectFit:
ratio = min(horizontalRatio, verticalRatio)
}

let rect = CGRect(x: 0, y: 0, width: self.size.width * ratio, height: self.size.height * ratio)
let rect = CGRect(x: 0, y: 0, width: size.width * ratio, height: size.height * ratio)

// Fix for a colorspace / transparency issue that affects some types of
// images. See here: http://vocaro.com/trevor/blog/2009/10/12/resize-a-uiimage-the-right-way/comment-page-2/#comment-39951
Expand All @@ -358,15 +358,15 @@ public extension UIImage {


//CGContextSetInterpolationQuality(context, CGInterpolationQuality(kCGInterpolationHigh.value))

// Draw into the context; this scales the image
CGContextDrawImage(context, rect, self.CGImage)

// Get the resized image from the context and a UIImage
let newImage = UIImage(CGImage: CGBitmapContextCreateImage(context)!, scale: self.scale, orientation: self.imageOrientation)
return newImage;
}


// MARK: Corner Radius

Expand All @@ -392,7 +392,7 @@ public extension UIImage {
let colorSpace = CGImageGetColorSpace(imageWithAlpha?.CGImage)
let bitmapInfo = CGImageGetBitmapInfo(imageWithAlpha?.CGImage)
let context = CGBitmapContextCreate(nil, width, height, bits, 0, colorSpace, bitmapInfo.rawValue)
let rect = CGRect(x: 0, y: 0, width: size.width*scale, height: size.height*scale)
let rect = CGRect(x: 0, y: 0, width: CGFloat(width)*scale, height: CGFloat(height)*scale)

CGContextBeginPath(context)
if (cornerRadius == 0) {
Expand Down Expand Up @@ -420,38 +420,38 @@ public extension UIImage {
}

/**
Creates a new image with rounded corners and border.
- Parameter cornerRadius: The corner radius.
- Parameter border: The size of the border.
- Parameter color: The color of the border.
- Returns A new image
*/
Creates a new image with rounded corners and border.
- Parameter cornerRadius: The corner radius.
- Parameter border: The size of the border.
- Parameter color: The color of the border.
- Returns A new image
*/
func roundCorners(cornerRadius:CGFloat, border:CGFloat, color:UIColor) -> UIImage?
{
return roundCorners(cornerRadius)?.applyBorder(border, color: color)
}

/**
Creates a new circle image.
- Returns A new image
*/
Creates a new circle image.
- Returns A new image
*/
func roundCornersToCircle() -> UIImage?
{
let shortest = min(size.width, size.height)
return cropToSquare()?.roundCorners(shortest/2)
}

/**
Creates a new circle image with a border.
- Parameter border :CGFloat The size of the border.
- Parameter color :UIColor The color of the border.
- Returns UIImage?
*/
Creates a new circle image with a border.
- Parameter border :CGFloat The size of the border.
- Parameter color :UIColor The color of the border.
- Returns UIImage?
*/
func roundCornersToCircle(border border:CGFloat, color:UIColor) -> UIImage?
{
let shortest = min(size.width, size.height)
Expand Down Expand Up @@ -532,5 +532,5 @@ public extension UIImage {
}
return placeholder
}

}
2 changes: 1 addition & 1 deletion AFImageHelper/AFImageVIewExtension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// AFImageViewExtension.swift
//
// AFImageHelper
// Version 3.0.1
// Version 3.0.2
//
// Created by Melvin Rivera on 7/23/14.
// Copyright (c) 2014 All Forces. All rights reserved.
Expand Down
14 changes: 4 additions & 10 deletions Demo/Base.lproj/Main.storyboard
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="7706" systemVersion="15A279b" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="PkK-Yq-iRC">
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="9531" systemVersion="15C50" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="PkK-Yq-iRC">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7703"/>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="9529"/>
</dependencies>
<scenes>
<!--View Controller-->
Expand All @@ -11,7 +12,6 @@
<collectionView key="view" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" dataMode="prototypes" id="XN2-u0-GSj">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<animations/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<collectionViewFlowLayout key="collectionViewLayout" minimumLineSpacing="0.0" minimumInteritemSpacing="10" id="2kr-zh-ESg">
<size key="itemSize" width="140" height="180"/>
Expand All @@ -21,28 +21,24 @@
</collectionViewFlowLayout>
<cells>
<collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" reuseIdentifier="Cell" id="PoI-kF-bIp" customClass="Cell" customModule="AFImageHelper" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="50" height="50"/>
<rect key="frame" x="10" y="85" width="140" height="180"/>
<autoresizingMask key="autoresizingMask"/>
<view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center">
<rect key="frame" x="0.0" y="0.0" width="140" height="180"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<imageView userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="A0P-dM-x7j">
<rect key="frame" x="0.0" y="0.0" width="140" height="140"/>
<animations/>
</imageView>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="Label" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="tHF-ui-OAV">
<rect key="frame" x="0.0" y="146" width="140" height="21"/>
<animations/>
<fontDescription key="fontDescription" name="HelveticaNeue-Light" family="Helvetica Neue" pointSize="17"/>
<color key="textColor" white="0.66666666666666663" alpha="1" colorSpace="calibratedWhite"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<animations/>
<color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/>
</view>
<animations/>
<connections>
<outlet property="imageView" destination="A0P-dM-x7j" id="utS-aT-MBW"/>
<outlet property="textLabel" destination="tHF-ui-OAV" id="CM6-io-V7W"/>
Expand All @@ -55,13 +51,11 @@
<subviews>
<label opaque="NO" userInteractionEnabled="NO" tag="1" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="Label" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="7QF-R9-6Hj">
<rect key="frame" x="10" y="17" width="550" height="53"/>
<animations/>
<fontDescription key="fontDescription" name="HelveticaNeue-Light" family="Helvetica Neue" pointSize="22"/>
<color key="textColor" red="1" green="0.0" blue="0.50196081399917603" alpha="1" colorSpace="calibratedRGB"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<animations/>
</collectionReusableView>
<connections>
<outlet property="dataSource" destination="PkK-Yq-iRC" id="i67-d7-tHh"/>
Expand Down
14 changes: 8 additions & 6 deletions Demo/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ class Cell: UICollectionViewCell {

class ViewController: UICollectionViewController {

let imageWidth = 140.0
let imageHeight = 140.0
let imageWidth = 140 * UIScreen.mainScreen().scale
let imageHeight = 140 * UIScreen.mainScreen().scale

var sections = [String]()
var items = [[CellItem]]()
Expand Down Expand Up @@ -52,7 +52,8 @@ class ViewController: UICollectionViewController {
// Text
sections.append("Text")
var text = [CellItem]()
if let image = UIImage(text: "M", font: UIFont.systemFontOfSize(64), color: UIColor.whiteColor(), backgroundColor: UIColor.redColor(), size: CGSize(width: imageWidth, height: imageHeight), offset: CGPoint(x: 0.0, y: 30.0)) {
let textSize = 64 * UIScreen.mainScreen().scale
if let image = UIImage(text: "M", font: UIFont.systemFontOfSize(textSize), color: UIColor.whiteColor(), backgroundColor: UIColor.redColor(), size: CGSize(width: imageWidth, height: imageHeight))?.roundCornersToCircle() {
text.append(CellItem(text: "Text Image", image: image))
}
items.append(text)
Expand All @@ -63,10 +64,11 @@ class ViewController: UICollectionViewController {
if let image = UIImage(named: "beach")?.roundCornersToCircle() {
corners.append(CellItem(text: "Circle", image: image))
}
if let image = UIImage(named: "beach")?.roundCornersToCircle(border: 60.0, color: UIColor.grayColor()) {
let border = 12 * UIScreen.mainScreen().scale
if let image = UIImage(named: "beach")?.roundCornersToCircle(border: border, color: UIColor.lightGrayColor()) {
corners.append(CellItem(text: "Circle + Border", image: image))
}
if let image = UIImage(named: "beach")?.roundCorners(12.0) {
if let image = UIImage(named: "beach")?.roundCorners(12) {
corners.append(CellItem(text: "Round Corners", image: image))
}
items.append(corners)
Expand All @@ -75,7 +77,7 @@ class ViewController: UICollectionViewController {
// Cropping
sections.append("Cropping")
var cropping = [CellItem]()
if let image = UIImage(named: "beach")?.crop(CGRect(x: 40.0, y: 40.0, width: 320.0, height: 100.0))?.applyPadding(6.0) {
if let image = UIImage(named: "beach")?.crop(CGRect(x: 40.0, y: 40.0, width: imageWidth, height: imageHeight/2)) {
cropping.append(CellItem(text: "Crop + Resize", image: image))
}
items.append(cropping)
Expand Down

0 comments on commit 85e58b9

Please sign in to comment.