Skip to content

Commit

Permalink
Switch to Swift 5
Browse files Browse the repository at this point in the history
  • Loading branch information
Petr Prokop committed Mar 30, 2021
1 parent 1379b20 commit 0cbb5e4
Show file tree
Hide file tree
Showing 6 changed files with 117 additions and 179 deletions.
191 changes: 97 additions & 94 deletions PPSwiftGifs/PPSwiftGifs.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,135 +6,138 @@
// Copyright (c) 2014 Peter Prokop. All rights reserved.
//

import Foundation
import UIKit
import CoreFoundation
import Foundation
import ImageIO
import UIKit

public class PPSwiftGifs
{
public class PPSwiftGifs {
// MARK: Public
public class func animatedImageWithGIFNamed(name: String!) -> UIImage? {
let screenScale = Int(UIScreen.mainScreen().scale)

public class func animatedImageWithGIF(named name: String!) -> UIImage? {
let screenScale = Int(UIScreen.main.scale)
let possibleScales = [1, 2, 3]
let orderedScales = [screenScale] + possibleScales.filter{$0 != screenScale}
let tmp = orderedScales.map{["@" + String($0) + "x", "@" + String($0) + "X"]}
let orderedSuffixes = tmp.reduce([], combine: +) + [""]
let orderedScales = [screenScale] + possibleScales.filter { $0 != screenScale }

let suffixes = orderedScales.map { ["@\($0)x", "@\($0)X"] }
let orderedSuffixes = suffixes.flatMap { $0 } + [""]

for suffix in orderedSuffixes {
if let url = NSBundle.mainBundle().URLForResource(name + suffix, withExtension: "gif") {
let source = CGImageSourceCreateWithURL(url, nil)
return animatedImageWithImageSource(source)
if let url = Bundle.main.url(forResource: name + suffix, withExtension: "gif"),
let source = CGImageSourceCreateWithURL(url as CFURL, nil)
{
return animatedImageWithImageSource(source: source)
}
}

return nil
}
public class func animatedImageWithGIFData(data: NSData!) -> UIImage? {
if let source = CGImageSourceCreateWithData(data, nil) {
return animatedImageWithImageSource(source)

public class func animatedImageWithGIF(data: Data) -> UIImage? {
if let source = CGImageSourceCreateWithData(data as NSData, nil) {
return animatedImageWithImageSource(source: source)
}

return nil
}

// MARK: Private
private class func animatedImageWithImageSource (source: CGImageSourceRef) -> UIImage? {
let (images, delays) = createImagesAndDelays(source);
let totalDuration = delays.reduce(0, combine: +)
let frames = frameArray(images, delays, totalDuration)


private class func animatedImageWithImageSource(source: CGImageSource) -> UIImage? {
let (images, delays) = createImagesAndDelays(source: source)
let totalDuration = delays.reduce(0, +)
let frames = frameArray(
images: images,
delays: delays,
totalDuration: totalDuration
)

// All durations in GIF are in 1/100th of second
let duration = NSTimeInterval(Double(totalDuration)/100.0)
let animation = UIImage.animatedImageWithImages(frames, duration: duration)
let duration = TimeInterval(Double(totalDuration) / 100.0)
let animation = UIImage.animatedImage(with: frames, duration: duration)

return animation
}
private class func createImagesAndDelays(source: CGImageSourceRef) -> (Array<CGImageRef>, Array<Int>) {

private class func createImagesAndDelays(source: CGImageSource) -> ([CGImage], [Int]) {
let count = Int(CGImageSourceGetCount(source))
var images = Array<CGImageRef>()
var delays = Array<Int>()
for i in 0 ..< count {
images.append(CGImageSourceCreateImageAtIndex(source, i, nil))
delays.append(delayForImageAtIndex(source, UInt(i)))

var images = [CGImage]()
var delays = [Int]()

for i in 0..<count {
images.append(CGImageSourceCreateImageAtIndex(source, i, nil)!)
delays.append(delayForImage(source: source, at: i))
}

return (images, delays)
}
private class func delayForImageAtIndex(source: CGImageSourceRef, _ i: UInt) -> Int {

private class func delayForImage(source: CGImageSource, at i: Int) -> Int {
var delay = 1
let properties = CGImageSourceCopyPropertiesAtIndex(source, Int(i), nil)
if (properties != nil) {
let gifDictionaryProperty = unsafeBitCast(kCGImagePropertyGIFDictionary, UnsafePointer<Void>.self)

let properties = CGImageSourceCopyPropertiesAtIndex(source, i, nil)

if properties != nil {
let gifDictionaryProperty = unsafeBitCast(kCGImagePropertyGIFDictionary, to: UnsafeRawPointer.self)
let gifProperties = CFDictionaryGetValue(properties, gifDictionaryProperty)

if (gifProperties != nil) {
let gifPropertiesCFD = unsafeBitCast(gifProperties, CFDictionary.self)

let unclampedDelayTimeProperty = unsafeBitCast(kCGImagePropertyGIFUnclampedDelayTime, UnsafePointer<Void>.self)
var number = unsafeBitCast(CFDictionaryGetValue(gifPropertiesCFD, unclampedDelayTimeProperty), NSNumber.self);

if (number.doubleValue == 0) {
let delayTimeProperty = unsafeBitCast(kCGImagePropertyGIFDelayTime, UnsafePointer<Void>.self)
number = unsafeBitCast(CFDictionaryGetValue(gifPropertiesCFD, delayTimeProperty), NSNumber.self);

if gifProperties != nil {
let gifPropertiesCFD = unsafeBitCast(gifProperties, to: CFDictionary.self)

let unclampedDelayTimeProperty = unsafeBitCast(
kCGImagePropertyGIFUnclampedDelayTime,
to: UnsafeRawPointer.self
)
var number = unsafeBitCast(
CFDictionaryGetValue(gifPropertiesCFD, unclampedDelayTimeProperty),
to: NSNumber.self
)

if number.doubleValue == 0 {
let delayTimeProperty = unsafeBitCast(kCGImagePropertyGIFDelayTime, to: UnsafeRawPointer.self)
number = unsafeBitCast(CFDictionaryGetValue(gifPropertiesCFD, delayTimeProperty), to: NSNumber.self)
}
if (number.doubleValue > 0) {
delay = lrint(number.doubleValue * 100);

if number.doubleValue > 0 {
delay = lrint(number.doubleValue * 100)
}
}
}
return delay;

return delay
}

private class func frameArray(images: Array<CGImageRef>, _ delays: Array<Int>, _ totalDuration: Int) -> Array<AnyObject> {
let delayGCD = gcd(delays)
let frameCount = totalDuration / delayGCD
var frames = Array<UIImage>()

private class func frameArray(images: [CGImage], delays: [Int], totalDuration: Int) -> [UIImage] {
let delayGCD = gcd(values: delays)
var frames = [UIImage]()
frames.reserveCapacity(images.count)
for i in 0 ..< images.count {
let frame = UIImage(CGImage: images[i], scale: UIScreen.mainScreen().scale, orientation: .Up)
for j in 0 ..< delays[i]/delayGCD {
frames.append(frame!)

for i in 0..<images.count {
let frame = UIImage(cgImage: images[i], scale: UIScreen.main.scale, orientation: .up)
for _ in 0..<delays[i] / delayGCD {
frames.append(frame)
}
}
return frames;

return frames
}

private class func gcd(values: Array<Int>) -> Int {
if values.count == 0 {
return 1;
}

var currentGCD = values[0]

for i in 0 ..< values.count {
currentGCD = gcd(values[i], currentGCD)
}

return currentGCD;

private class func gcd(values: [Int]) -> Int {
return values.reduce(1, gcd)
}

private class func gcd(var a: Int, var _ b: Int) -> Int {
while (true) {
var r = a % b
if (r == 0) {

private class func gcd(_ num1: Int, _ num2: Int) -> Int {
var a = num1
var b = num2

while true {
let r = a % b
if r == 0 {
return b
}
a = b;
b = r;
a = b
b = r
}
}
}
17 changes: 13 additions & 4 deletions PPSwiftGifsExample/PPSwiftGifsExample.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,7 @@
developmentRegion = English;
hasScannedForEncodings = 0;
knownRegions = (
English,
en,
Base,
);
Expand Down Expand Up @@ -482,11 +483,12 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.1;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
};
name = Debug;
};
Expand Down Expand Up @@ -518,9 +520,10 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.1;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_VERSION = 5.0;
VALIDATE_PRODUCT = YES;
};
name = Release;
Expand Down Expand Up @@ -602,11 +605,13 @@
);
INFOPLIST_FILE = PPSwiftGifs/Info.plist;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 8.3;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
"IPHONEOS_DEPLOYMENT_TARGET[sdk=macosx*]" = 13.1;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_OBJC_BRIDGING_HEADER = "";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
Expand All @@ -626,11 +631,13 @@
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = PPSwiftGifs/Info.plist;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 8.3;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
"IPHONEOS_DEPLOYMENT_TARGET[sdk=macosx*]" = 13.1;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_OBJC_BRIDGING_HEADER = "";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
Expand Down Expand Up @@ -711,6 +718,7 @@
0DFFAEAB1AFF49F3009E1DFB /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
0DFFAEAF1AFF49F3009E1DFB /* Build configuration list for PBXNativeTarget "PPSwiftGifsTests" */ = {
isa = XCConfigurationList;
Expand All @@ -719,6 +727,7 @@
0DFFAEAD1AFF49F3009E1DFB /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
Expand Down
25 changes: 1 addition & 24 deletions PPSwiftGifsExample/PPSwiftGifsExample/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,33 +14,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}

func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


}

17 changes: 5 additions & 12 deletions PPSwiftGifsExample/PPSwiftGifsExample/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,14 @@ class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()

imageView1.image = PPSwiftGifs.animatedImageWithGIFNamed("Loading")
imageView2.image = PPSwiftGifs.animatedImageWithGIFNamed("VariableDuration")
imageView1.image = PPSwiftGifs.animatedImageWithGIF(named: "Loading")
imageView2.image = PPSwiftGifs.animatedImageWithGIF(named: "VariableDuration")

if let url = NSBundle.mainBundle().URLForResource("Loading", withExtension: "gif") {
if let data = NSData(contentsOfURL: url) {
imageView3.image = PPSwiftGifs.animatedImageWithGIFData(data)
if let url = Bundle.main.url(forResource: "Loading", withExtension: "gif") {
if let data = try? Data(contentsOf: url) {
imageView3.image = PPSwiftGifs.animatedImageWithGIF(data: data)
}
}
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


}

Loading

0 comments on commit 0cbb5e4

Please sign in to comment.