• Stars
    star
    2,206
  • Rank 20,916 (Top 0.5 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 9 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

High performance and delightful way to play with APNG format in iOS.

APNGKit

APNGKit is a high performance framework for loading and displaying APNG images in iOS and macOS. It's built with high-level abstractions and brings a delightful API. Since be that, you will feel at home and joy when using APNGKit to play with images in APNG format.

APNG, what and why?

The Animated Portable Network Graphics (APNG) is a file format extending the well-known PNG format. It allows for animated PNG files that work similarly to animated GIF files, while supporting 24-bit images and 8-bit transparency not available for GIFs. This means much better quality of animation. At the same time, the file size is comparable to or even less than, if created carefully, GIFs.

Talk is cheap; show me the image. You can click on the image to see how it looks like when animating.

APNGKit Demo

That's cool. APNG is much better! But wait...why haven't I heard about APNG before? It is not a popular format, so why should I use it in my next great iOS/macOS app?

Good question! APNG is an excellent extension for regular PNG, and it is also very simple to use and not conflicting with current PNG standard (It consists a standard PNG header, so if your platform does not support APNG, it will be recognized as a normal PNG with its first frame being displayed as a static image). But unfortunately, it is a rebel format so that it is not accepted by the PNG group. However, it is accepted by many vendors and is even mentioned in W3C Standards. There is another format called MNG (Multiple-image Network Graphics), which is created by the same team as PNG. It is a comprehensive format, but very very very (้‡่ฆ็š„ไบ‹่ฆ่ฏดไธ‰้) complex. It is so complex that despite being a "standard", it was almost universally rejected. There is only one "popular" browser called Konqueror(at least I have used it before when I was in high school) that supports MNG, which is really a sad but reasonable story.

Even though APNG is not accepted currently, we continue to see the widespread implementation of it. Apple recently supported APNG in both desktop and mobile Safari. Microsoft Edge and Chrome are also considering adding APNG support since it is already officially added in WebKit core.

APNG is such a nice format to bring users much better experience of animating images. The more APNG is used, the more recognition and support it will get. Not only in the browsers world, but also in the apps we always love. That's why I created this framework.

Installation

Requirement

iOS 9.0+ / macOS 10.11+ / tvOS 9.0+

Swift Package Manager

The recommended way to install APNGKit is to use Swift Package Manager. Adding it to your project with Xcode:

CocoaPods

CocoaPods is a dependency manager for Cocoa projects.

$ gem install cocoapods

To integrate APNGKit into your Xcode project using CocoaPods, specify it in your Podfile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
use_frameworks!

target 'your_app' do
 ย pod 'APNGKit', '~> 2.0'
end

Then, run the following command:

$ pod install

You should open the {Project}.xcworkspace instead of the {Project}.xcodeproj after you installed anything from CocoaPods.

For more information about how to use CocoaPods, I suggest this tutorial.

Usage

Basic

Import APNGKit into your source files in which you want to use the framework.

import APNGKit

Load an APNG Image

// Load an APNG image from file in main bundle
var image = try APNGImage(named: "your_image")

// Or
// Load an APNG image from file at specified path
if let url = Bundle.main.url(forResource: "your_image", withExtension: "apng") {
    image = try APNGImage(fileURL: path)
}

// Or
// Load an APNG image from data
let data: Data = ... // From disk or network or anywhere else.
image = try APNGImage(data: data)

You may notice that all initializers are throwable. If anything is wrong during creating the image, it let you know the error explicitly and you have a chance to handle it. We will cover the error handling soon later.

Display an APNG Image

When you have an APNGImage object, you can use it to initialize an image view and display it on screen with an APNGImageView, which is a subclass of UIView or NSView:

let image: APNGImage = ... // You already have an APNG image object.

let imageView = APNGImageView(image: image)
view.addSubview(imageView)

Start animation

The animation will be played automatically as soon as the image view is created with a valid APNG image. If you do not want the animation to be played automatically, set the autoStartAnimationWhenSetImage property to false before you assign an image:

let imageView = APNGImageView(frame: .zero)
imageView.autoStartAnimationWhenSetImage = false
imageView.image = image

// Start the animation manually:
imageView.startAnimating()

XIB or Storyboard

If you are an Interface Builder lover, drag a UIView (or NSView) (Please note, not a UIImageView or NSImageView) to the canvas, and modify its class to APNGImageView. Then, you can drag an IBOutlet and play with it as usual, such as setting its image property.

Delegates

APNG defines the play loop count as numberOfPlays in APNGImage, and APNGKit respects it by default. To inspect the end of each loop, register yourself as a delegate of APNGImageView.onOnePlayDone:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let imageView = APNGImageView(image: image)
        imageView.onOnePlayDone.delegate(on: self) { (self, count) in
            print("Played: \(count)")
        }
    }
}

When numberOfPlays is nil, the animation will be played forever. If it is a limited non-zero value, the animation will be stopped at the final frame when the loop count reaches the limit. To inspect the whole animation is done, use onAllPlaysDone:

imageView.onAllPlaysDone.delegate(on: self) { (self, _) in
    print("All done.")
}

APNGKit loads the data in a streaming way by default, it reads the frame information while playing the animation. Since APNG encodes the duration in each frame, it is not possible to get the whole animation duration before loading all frames information. Before the first reading pass finishes, you can only get a partial duration for loaded frames. To get the full duration, use APNGImage.onFramesInformationPrepared:

let image = try APNGImage(named: "image")
image.onFramesInformationPrepared.delegate(on: self) { (self, _) in
    switch image.duration {
        case .full(let duration):
            print("Full duration: \(duration)")
        case .partial:
            print("This should not happen.")
    }
}

imageView.image = image

Or, you can specify the .fullFirstPass option while creating the APNGImage. It reads all frames before starting rendering and animating the image:

let image = try APNGImage(named: "image", options: [.fullFirstPass])
print(image.duration) // .full(duration)

APNGKit provides a few other reading options. Please let me skip it for now and you can check them in documentation.

Error handling

While creating image

Creating an APNGImage can throw an error if anything goes wrong. All possible errors while decoding are defined as an APNGKitError.decoderError. When an error happens while creating the image, you are expected to check if it should be treated as a normal static image. If so, try to set it as the static image:

do {
    let image = try APNGImage(named: data.imageName)
    imageView.image = image
} catch {
    if let normalImage = error.apngError?.normalImage {
        imageView.staticImage = normalImage
    } else {
        print("Error: \(error)")
    }
}

While playing animation

If some frames are broken, the default image defined in APNG should be displayed as a fallback. You can get this in APNGKit for free. To get notified when this happens, listen to APNGImageView.onFallBackToDefaultImage:

imageView.onDecodingFrameError.delegate(on: self) { (self, error) in
    print("A frame cannot be decoded. After this, either onFallBackToDefaultImage or onFallBackToDefaultImageFailed happens.")
}

imageView.onFallBackToDefaultImage.delegate(on: self) { (self, _) in
    print("Fall back to default image.")
}
imageView.onFallBackToDefaultImageFailed.delegate(on: self) { (self, error) in
    print("Tried to fall back to default image, but it fails: \(error)")
}

PNG compression

Xcode will compress all PNG files in your app bundle when you build the project. Since APNG is an extension format of PNG, Xcode will think there are redundancy data in that file and compress it into a single static image. When this happens, you may inspect a log message from APNGKit:

CgBI chunk found. It seems that the input image is compressed by Xcode and not supported by APNGKit. Consider to rename it to apng to prevent compressing.

Usually this is not what you want when working with APNG. You can disable the PNG compression by setting "COMPRESS_PNG_FILES" to NO in the build settings of your app target. However, it will also prevent Xcode to optimize your other regular PNGs.

A better approach would be renaming your APNG files with an extension besides of "png". If you do so, Xcode will stop recognizing your APNG files as PNG format, and will not apply compression on them. A suggested extension is "apng", which will be detected and handled by APNGKit seamlessly.

Acknowledgement

The demo elephant image in README file is stolen from ICS Lab, you can find the original post here.

Reference

If you are interested in APNG, you can know more about it from the links below (some of them are written in Chinese).

APNGKit can only load and display APNG image now. The creating feature will be developed later. If you need to create APNG file now, I suggest using iSparta or apngasm instead for now.

License

APNGKit is released under the MIT license. See LICENSE for details.

More Repositories

1

Kingfisher

A lightweight, pure-Swift library for downloading and caching images from the web.
Swift
23,065
star
2

VVDocumenter-Xcode

Xcode plug-in which helps you write documentation comment easier, for both Objective-C and Swift.
Objective-C
8,329
star
3

FengNiao

A command line tool for cleaning unused resources in Xcode.
Swift
3,382
star
4

Rainbow

Delightful console output for Swift developers.
Swift
1,839
star
5

Hedwig

Send email to any SMTP server like a boss, in Swift and cross-platform
Swift
1,117
star
6

VVBlurPresentation

A simple way to present a view controller with keeping the blurred previous one.
Objective-C
894
star
7

RandomColorSwift

An attractive color generator for Swift. Ported from randomColor.js.
Swift
628
star
8

XUPorter

Add files and frameworks to your Xcode project after it is generated by Unity 3D.
C#
587
star
9

VVSpringCollectionViewFlowLayout

A spring-like collection view layout. The same effect like iOS7's Message.app
Objective-C
576
star
10

vno-jekyll

Another ported theme for Jekyll
SCSS
544
star
11

vno

Vno, just another ghost theme
CSS
518
star
12

Easy-Cal-Swift

Overload +-*/ operator for Swift, make it easier to use (and not so strict)
Swift
273
star
13

OneV-s-Den

Blog
SCSS
212
star
14

VVImageTint

UIImage category for image tint. For my blog post http://onevcat.com/2013/04/using-blending-in-ios/
Objective-C
193
star
15

UniWebView-Docs

Documentation of UniWebView Project
JavaScript
192
star
16

VCTransitionDemo

A simple demo indicates how to make a custom view controller transition in iOS 7
Objective-C
189
star
17

UserNotificationDemo

Demo project to show how to use UserNotifications framework in iOS 10
Swift
152
star
18

iOSWeekly

iOS Weekly issue for InfoQ CN
133
star
19

ToDoDemo

State-based View Controller demo
Swift
125
star
20

ObservationBP

Proof of concept for back-porting Observation framework to earlier iOS versions
Swift
113
star
21

DebuggableContext

Provides an easy to use action sheet for debugging purpose when shaking your iOS device.
Swift
97
star
22

resume

JavaScript
87
star
23

ComponentNetworking

Swift
83
star
24

swift-ui-book-issue

76
star
25

AddressParser

Email address parser.
Swift
70
star
26

Delegate

A meta library to provide a better `Delegate` pattern.
Swift
67
star
27

SpriteKitSimpleGame

A demo for starting using SpriteKit. Port famous Cocos2DSimpleGame to SpriteKit.
Objective-C
60
star
28

WatchWeather

Swift
47
star
29

MimeType

Get MIME type string from the extension of a file name
Swift
42
star
30

TimerExtensionDemo

A demo to show how to write a today extension.
Swift
41
star
31

ClockFaceView

A demo project for my blog post
Swift
31
star
32

UITestDemo

UITestDemo
Swift
21
star
33

VVStack

Just a TDD demo with XCTest and Kiwi
Objective-C
20
star
34

Noti

Swift
19
star
35

JekyllScroll

JekyllScroll is a theme for Jekyll.
CSS
19
star
36

DispatchMemoryLeakDemo

A demo that reproduce memory leak in iOS 9.2
Swift
19
star
37

VVBorderTimer

An easy border timer with configurable time, corner radius, line width and colors.
Objective-C
17
star
38

Notes

My Notes: http://notes.onevcat.com
17
star
39

lgtm-images

LGTM images collection
Swift
16
star
40

UniWebView-Deprecated

A universal webview plugin for Unity3D. Work with iOS, Android and Mac, using javascript to interact with Unity3D.
Objective-C
14
star
41

UnpauseMe

Script for Unity3D, unpause Unity3D animations or particles when set Time.timeScale = 0.
C#
14
star
42

PhotoData_Kiwi

Use Kiwi to replace objc.io's first issue. Just a demo for Kiwi and my post.
Objective-C
13
star
43

Swift-CI

Swift CI script. Stolen from vapor.
Shell
13
star
44

CounterDemo

A demo app for studying of TCA
Swift
12
star
45

check-lfs

A command-line tool to check binary file committed to a repo.
Swift
11
star
46

Kingfisher-Crash

Crash sample of Kingfisher SwiftUI with SPM on Xcode 11.2 beta
Swift
10
star
47

TexasPoker

A client of Texas Poker
Objective-C
9
star
48

NeuralNetworkLearning

Swift
9
star
49

XcodeScheme

9
star
50

YYTextSample

Sample project for a layout issue in iOS 10
Swift
9
star
51

pokemaster-images

Images for PokeMaster
8
star
52

KeyboardScrollingIssue

Swift
7
star
53

apple-versions

Astro
7
star
54

VVPluginDemo

A demo for how to make a simple Xcode 4 plug-in.
Objective-C
7
star
55

LineSDK-Integration

Integration Test Cases for LINE SDK Swift
Ruby
7
star
56

onevcat

6
star
57

VVPerlBBS

BBS with Perl. Powered by OneV's Den.
Perl
5
star
58

submail-provider

Submail email provider for Vapor
Swift
4
star
59

MwfTableViewController

Extension to UITableViewController in attempt to provide additional features that are reusable in most scenarios.
Objective-C
4
star
60

Flower-Data-Set

Python
4
star
61

GitHubActionPlayground

4
star
62

elm-2048

Practice my elm understanding
Elm
3
star
63

ChatBot

JavaScript
3
star
64

Math.swift

Math
Swift
3
star
65

onevcat.github.com

It's a user page
3
star
66

beginning-elm

JavaScript
3
star
67

LandscapeViewControllerDemo

Just a demo
Objective-C
3
star
68

LearningPerl

It's a repo for Perl learning to get prepared for future working in Kayac.
Objective-C
3
star
69

advent2021

For fun
Swift
2
star
70

qixia.wang

2
star
71

GoogleInteractiveMediaAds-Carthage

2
star
72

LazyContainerBug

State of cells in "lazy" container is lost, if the cell is embedded in a stack
Swift
2
star
73

objc-image-packer

Book build image for ObjCCN
HCL
2
star
74

cool-lang

COOL Lang
Java
2
star
75

JBAlertView

JBAlertView is the new AlertView for showing different alerts type (default, connection, error, ...)
Objective-C
2
star
76

github-battle

Typescript version of GitHub Battle
TypeScript
2
star
77

KF-issue-1931

Swift
1
star
78

VVAlertBanner

A alert banner view which could queue the alert and shou them each by each.
Objective-C
1
star
79

Kingfisher-TestImages

Test images for Swift image downloading framework - Kingfisher.
1
star
80

SPMConfigDemo

Swift
1
star
81

Kingfisher-Review-Sample

Swift
1
star