-
Notifications
You must be signed in to change notification settings - Fork 1
/
STGIFMaker.swift
68 lines (53 loc) · 1.88 KB
/
STGIFMaker.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//
// STGIFMaker.swift
// STMovingImages
//
// Created by nst on 21/11/15.
// Copyright © 2015 Nicolas Seriot. All rights reserved.
//
#if os(OSX)
import AppKit
import CoreServices
public typealias STImage = NSImage
#elseif os(iOS)
import UIKit
import MobileCoreServices
import CoreGraphics
import ImageIO
public typealias STImage = UIImage
#endif
public class STGIFMaker {
let imageDestination : CGImageDestination
let outPath : String
init?(destinationPath: String, loop: Bool) {
guard let id = CGImageDestinationCreateWithURL(
URL(fileURLWithPath: destinationPath) as CFURL,
kUTTypeGIF,
0,
nil) else {
return nil
}
self.imageDestination = id
self.outPath = destinationPath
let loopCount = loop ? 0 : 1
let gifProperties = [ kCGImagePropertyGIFDictionary as String : [kCGImagePropertyGIFLoopCount as String:loopCount] ] as CFDictionary
CGImageDestinationSetProperties(imageDestination, gifProperties)
}
func append(image : STImage, duration : Double) {
#if os(OSX)
let optCGImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil)
#elseif os(iOS)
let optCGImage = image.cgImage
#endif
guard let cgImage = optCGImage else { assertionFailure(); return }
let frameProperties = [ kCGImagePropertyGIFDictionary as String : [kCGImagePropertyGIFDelayTime as String:duration] ] as CFDictionary
CGImageDestinationAddImage(imageDestination, cgImage, frameProperties)
}
func write() -> Bool {
let success = CGImageDestinationFinalize(imageDestination)
if success {
print("-- wrote \(outPath)")
}
return success
}
}