Spine iOS Runtime Documentation

Licensing

Please see the Spine Runtimes License before integrating the Spine Runtimes into your applications.

Getting Started

The Spine iOS runtime is implemented using a thin wrapper around spine-cpp. It can be run both using UIKit and SwiftUI. Both Swift and Objective-C are supported.

It is using Metal for rendering and supports all Spine features except tint black.

Installation

Spine iOS is supported from iOS 13 onwards. To use Spine iOS in your project, you can either install it using the Swift Package Manager or CocoaPods

Ensure that the major.minor version of the spine-runtimes repo branch matches the major.minor Spine Editor version you are exporting from. See Spine Versioning for more information.

Swift Package Manager

Add the Spine iOS SPM package to your project:

  1. Open Xcode and your project.
  2. Navigate to Project Settings: Click on your project in the Project Navigator and select the project, right above the targets.
  3. Select Swift Packages: Click on the Package Dependencies tab.
  4. Add Package: Click + and enter git@github.com:EsotericSoftware/spine-runtimes.git in the search field.
  5. Dependency Rule: Select Commit and enter the most recent full commit hash in the major.minor branch you want to support.
  6. Finish: Click Next and then Finish after Xcode resolves the package.

You also need to enable C++ support:

  1. Navigate to Project Settings: Click your apps main target.
  2. Open Built Settings tab: Search for C++ and Objective-C Interoperability
  3. Select C++ / Objective-C++

CocoaPods

Due to the nature of how versioning works, Spine iOS is not part of the public CocoaPods index. You have to link to the .podspec files in order to add it in your Podfile. Make sure to use the correct major.minor branch.

python
# Uncomment the next line to define a global platform for your project
platform :ios, '13.0'

target 'Spine iOS Example' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!

pod '
Spine', :podspec => 'https://raw.githubusercontent.com/EsotericSoftware/spine-runtimes/4.2/Spine.podspec'
pod 'SpineCppLite', :podspec => 'https://raw.githubusercontent.com/EsotericSoftware/spine-runtimes/4.2/SpineCppLite.podspec'
pod 'SpineShadersStructs', :podspec => 'https://raw.githubusercontent.com/EsotericSoftware/spine-runtimes/4.2/SpineShadersStructs.podspec'
end

Usage

In both cases you can now import Spine in your Swift file:

Swift
import Spine

Samples

The Spine iOS runtime includes several samples that showcase its feature set.

You can run the example project following these steps:

  1. Install Xcode on your mac
  2. Clone the spine-runtimes repository: git clone https://github.com/esotericsoftware/spine-runtimes
  3. Open spine-runtimes/spine-ios/Example/Spine iOS Example.xcodeproj with Xcode

Alternatively, you can also open spine-runtimes/spine-ios/Example - Cocoapods/Spine iOS Example.xcodeproj to see how Spine iOS is imported using CocoaPods.

All samples listed below support SwiftUI previews and can be rendered in the canvas, right in Xcode.

The example project contains the following examples:

  • SimpleAnimation.swift: demonstrates the basic use of SpineView and SpineController to load an exported Spine skeleton, display it in the view, and playback a specific animation.
  • PlayPauseAnimation.swift: demonstrates how to pause and resume an animation.
  • AnimationStateEvents.swift: demonstrates how set a slot's color, how to queue multiple animations, and how to to listen for animation state events.
  • DebugRendering.swift: shows how to perform custom drawing on top of the rendered skeleton via the SpineController onAfterPaint callback.
  • DressUp.swift: demonstrates Spine's skins feature as well as rendering a skeleton to a thumbnail for use in a character creation UI.
  • IKFollowing.swift: demonstrates how to let the user drag one of the skeleton's bones via touch input.
  • DisableRendering.swift: Demonstrates how to disable rendeing when the SpineView moves off screen. This is important if you need to preserve CPU/GPU resources.
  • SimpleAnimationViewController.m: Demonstates how to use Spine iOS with UIKit and Objective-C.

Updating the Spine iOS Runtime

Before updating your project's Sine iOS runtime, please consult our guide on Spine editor and runtime version management.

For CocoaPods, link to the correct major.minor branch.

For SPM, choose the correct commit hash from the correct major.minor branch.

Note: If you change the major.minor version of the Spine iOS package, you have to re-export your Spine skeletons with the same Spine Editor major.minor version!

Using Spine iOS

The Spine iOS runtime is an idiomatic wrapper around the generic spine-cpp which supports loading, playback and manipulation of animations created with Spine. The Spine iOS runtime exposes almost all of the spine-cpp API as idiomatic Swift and provides SwiftUI and UIKit specific classes to easily display and interact with Spine skeletons.

The Spine iOS runtime supports all Spine features except tint black.

Asset Management

Exporting for Spine iOS

Please follow the instructions in the Spine User Guide on how to

  1. Export skeleton & animation data
  2. Export texture atlases containing the images of your skeleton

An export of the skeleton data and texture atlas of your skeleton will yield the following files:

  1. skeleton-name.json or skeleton-name.skel, containing your skeleton and animation data.
  2. skeleton-name.atlas, containing information about the texture atlas.
  3. One or more .png files, each representing on page of your texture atlas containing the packed images your skeleton uses.

Note: You should prefer binary skeleton exports over JSON exports, as they are smaller in size and faster to load.

The files can be loaded via Spine iOS classes like Atlas, SkeletonData, SkeletonDrawable, and SpineView.

Note: If you are using non-premultiplied assets, you need to disable Compress PNG Files and Remove Text Metadata From PNG Files in your application targets build settings.

Updating Spine Assets

During development, you may frequently update your Spine skeleton data and texture atlas files. You can simply overwrite these source files (.json, .skel, .atlas, .png) by re-exporting from the Spine Editor and replacing the existing files in your Xcode project.

Ensure that the major.minor version of Spine iOS matches the major.minor Spine Editor version you are exporting from. See Spine Versioning for more information.

Core classes

The Spine iOS API is built on top of the generic spine-cpp runtime, which provides platform independent core classes and algorithms to load, query, modify, and animate Spine skeletons. The core classes are exposed as idiomatic Swift classes.

Here, we will briefly discuss the most important core classes that you will encounter in your day-to-day use of Spine iOS. Please consult the Spine Runtimes Guide for a detailed overview of the Spine Runtimes architecture, core classes, and API usage.

The Atlas class stores the data loaded from an .atlas file and its corresponding .png image files.

The SkeletonData class stores the data loaded from a .json or .skel skeleton file. The skeleton data contains information about the bone hierarchy, slots, attachments, constraints, skins, and animations. A SkeletonData instance is usually loaded by also providing an Atlas from which it sources the images to be used by the skeleton it represents. It serves as a blueprint for creating Skeleton instances. Multiple skeletons can be instantiated from the same atlas and skeleton data, which then share the loaded data, minimizing both load times and memory consumption at runtime.

The Skeleton class stores an instance of a skeleton, created from a SkeletonData instance. A skeleton stores its current pose, that is the position of bones and the current configuration of slots, attachments, and active skin. The current pose can be computed by either manually modifying the bone hierarchy, or, more commonly, by applying animations via an AnimationStateWrapper.

The AnimationStateWrapper holds the AnimationState class, which is responsible for keeping track of which animation(s) should be applied to a skeleton, advancing and mixing those animations based on the elapsed time between the last and current rendering frame, and applying the animations to a skeleton instance, thereby setting its current pose. The AnimationState queries an AnimationStateData instance to retrieve mixing times between animations, or fetches the default mix time if no mixing time is available for a pair of animations.

The Spine iOS runtime builds on top of these core classes.

SpineView / SpineUIView

/img/spine-runtimes-guide/spine-ios/simple-animation.png

The SpineView struct is a UIViewRepresentable around SpineUIView, so the latter can be used in SwiftUI projects. SpineUIView is a subclass of MTKView

Going forward, we will be using SpineView when refering to either one of them.

A SpineView is responsible for loading and displaying a Spine skeleton. At a minimum, the view needs to know from where to load the skeleton and atlas files, and it can receive a SpineController instance that is responsible for modifying the state of the widget, such as setting an animation, or changing the skin of the skeleton.

The SpineController is an ObservableObject and be held inside a @State variable. In the simplest case, a SpineView can be instantiated inside another views body like this:

Swift
@StateObject
var controller = SpineController(
   onInitialized: { controller in
      controller.animationState.setAnimationByName(
         trackIndex: 0,
         animationName: "walk",
         loop: true
      )
   }
)

var body: some View {
   SpineView(
      from: .bundle(atlasFileName: "spineboy.atlas", skeletonFileName: "spineboy-pro.skel"),
      controller: controller,
      mode: .fit,
      alignment: .center
   )
}

Upon instantiation, the SpineView will asynchronously load the specified files and construct the underlying core class instances from them, namely instances of Atlas, SkeletonData, Skeleton, AnimationStateData, and AnimationState.

Once loading is complete, the SpineController onInitialized is called, allowing it to modify the state of the widget, such as setting one or more animations, manipulating the bone hierarchy, or modifying the skin of the skeleton. See the section on SpineController below.

The SpineView class takes the SpineViewSource enum as its first parameter, to load skeleton and atlas files from different sources:

  • SpineViewSource.bundle loads files from the main bundle, or a provided bundle.
  • SpineViewSource.file loads files from the file system.
  • SpineViewSource.http loads files from URLs.
  • SpineViewSource.drawable() constructs a view from a SkeletonDrawable. This is useful when the skeleton data should be preloaded, cached, and/or shared between SpineView instances. See the section "Pre-loading and sharing skeleton data" below.

Additionally, SpineView has optional arguments that let you further define how the Spine skeleton is fitted and aligned inside the view, and how the view is sized.

mode: How the skeleton is fitted inside SpineUIView. Per default, it is .fit

  • mode, how the skeleton is fitted inside SpineUIView. Per default, it is .fit
  • alignment, how the skeleton is alignment inside SpineUIView. Per default, it is .center
  • boundsProvider, used to calculate the pixel size of the bounding box to be used for the skeleton when computing the fit and alignment. By default, the skeleton's setup pose bounding box is used. See the class documentation for SetupPoseBounds, RawBounds, and SkinAndAnimationBounds for additional information.
  • backgroundColor: The background color of the view. Per defaut, UIColor.clear is used

The SpineView has an addition optional binding parameter isRendering, through which rendering can be disabled. See the DisableRendering.swift example for more information.

SpineController

A SpineController controls how the skeleton of a SpineView is animated and rendered. The controller is provided with a set of optional callbacks as constructor arguments, which are called at specific times during the life-time of the SpineView.

The controller exposes the skeleton state through getters returning Spine Runtimes API objects such as the Atlas, SkeletonData, Skeleton, and AnimationState, through which the state can be manipulated. See the Spine Runtimes Guide, and the class documentation for more information.

Upon initialization of a SpineView, the controller's onInitialized() callback method is invoked once. This method can be used to setup the initial animation(s) to be played back, or set the skin of the skeleton, among other things.

After initialization is complete, the SpineView is rendered continuously at the screen refresh rate. Each frame, the AnimationState is updated based on the currently queued animations, and applied to the Skeleton.

Next, the optional onBeforeUpdateWorldTransforms() callback is invoked, which can modify the skeleton before its current pose is calculated using Skeleton.updateWorldTransform().

After the current pose has been calculated, the optional onAfterUpdateWorldTransforms() callback is invoked, which can further modify the current pose before the skeleton is rendered. This is a good place to manually position bones.

Before the skeleton is rendered by the SpineView, the optional onBeforePaint() callback is invoked, which allows rendering backgrounds or other objects that should go behind the skeleton in your view hierarchy.

After the SpineWidget has rendered the current skeleton pose, the optional onAfterPaint() callback is invoked, which allows rendering additional objects on top of the skeleton in your view hierarchy.

By default, the view updates and renders the skeleton every frame. The SpineController.pause() method can be used to pause updating and rendering the skeleton. The SpineController.resume() method resumes updating and rendering the skeleton. The SpineController.isPlaying property reports the current playback state. See the AnimationStateEvents.swift example.

SkeletonDrawableWrapper / SkeletonDrawable

A SkeletonDrawableWrapper holds SkeletonDrawable and bundles loading, storing, updating, and rendering a Skeleton and its associated AnimationState into a single, easy to use class. The SpineView encapsulates the state of the skeleton it displays via an instance of a SkeletonDrawableWrapper.

Use the fromBundle(), fromFile(), or fromHttp() methods to construct a SkeletonDrawableWrapper from file assets. To share Atlas and SkeletonData among multiple SkeletonDrawableWrapper instances, instantiate the drawables via the constructor, passing the same atlas and skeleton data to each of them.

The SkeletonDrawableWrapper exposes the SkeletonDrawable, Skeleton, AnimationState and AnimationStateWrapper to query, modify, and animate the skeleton. It also exposes the Atlas and SkeletonData from which the skeleton and animation state have been constructed.

To animate the skeleton, queue animations on one or more tracks via the AnimationState API, such as AnimationState.setAnimation() or AnimationState.addAnimation().

To update the animation state, apply it to the skeleton, and update the current skeleton pose, call the SkeletonDrawableWrapper.update() method, providing it a delta time in seconds to advance the animations.

To render the current pose of the Skeleton as a CGImage, use SkeletonDrawableWrapper/renderToImage(size:backgroundColor:scaleFactor:).

The SkeletonDrawable stores objects allocated on the native heap. The native objects need to be manually disposed of via a call to SkeletonDrawable.dispose() if the SkeletonDrawable is no longer needed. Not doing so will result in a native memory leak.

Note: SpineController does this automatically when beeing deinitialized. However, if you hold the SkeletonDrawableWrapper outside of SpineController, you are responsible for disposing like described above. In this case, set the optional disposeDrawableOnDeInit constructor parameter of SpineController to false.

Applying Animations

Applying animations to a skeleton displayed by a SpineView is done through the AnimationState in the callbacks of a SpineController.

Note: See Applying Animations in the Spine Runtimes Guide for more in-depth information, specifically about animation tracks and animation queueing.

To set a specific animation on track 0, call AnimationState.setAnimationByName():

Swift
@StateObject
var controller = SpineController(
   onInitialized: { controller in
       // Set the walk animation on track 0, let it loop
      controller.animationState.setAnimationByName(
         trackIndex: 0,
         animationName: "walk",
         loop: true
      )
   }
)

The first parameter specifies the track, the second parameter is the name of the animation, and the third parameter defines whether to loop the animation.

You can queue multiple animations:

Swift
controller.animationState.setAnimationByName(trackIndex: 0, animationName: "walk", loop: true)
controller.animationState.addAnimationByName(trackIndex: 0, animationName: "jump", loop: false, delay: 2)
controller.animationState.addAnimationByName(trackIndex: 0, animationName: "run", loop: true, delay: 0)

The first parameter to addAnimationByName() is the track. The second parameter is the name of the animation. The third parameter defines whether to loop the animation. The final parameter specifies the delay in seconds, after which this animation should replace the previous animation on the track.

In the example above, the "walk" animation is played back first. 2 seconds later, the "jump" animation is played back once, followed by a transition to the "run" animation, which will be looped.

When transitioning from one animation to another, AnimationState will mix the animations for a specificable duration. These mix times are defined in an AnimationStateData instance, from which the AnimationState retrieves mix times.

The AnimationStateData instance is also available through the controller. You can set the default mix time, or the mix time for a specific pair of animations:

Swift
controller.animationStateData.defaultMix = 0.2
controller.animationStateData.setMixByName(fromName: "walk", toName: "jump", duration: 0.1)

When setting or adding an animation, a TrackEntry object is returned, which allows further modification of that animation's playback. For example, you can set the track entry to reverse the animation playback:

Swift
var entry = controller.animationState.setAnimationByName(trackIndex: 0, animationName: "walk", loop: true)
entry.reverse = true

See the TrackEntry class documentation for more options.

Note: Do not hold on to TrackEntry instances outside the function you are using them in. Track entries are re-used internally and will thus become invalid once the animation it represents has been completed.

You can set or queue empty animations on an animation track to smoothly reset the skeleton back to its setup pose:

Swift
controller.animationState.setEmptyAnimation(trackIndex: 0, mixDuration: 0.5)
controller.animationState.addEmptyAnimation(trackIndex: 0, mixDuration: 0.5, delay: 0.5)

The first parameter to setEmptyAnimation() specifies the track. The second parameter specifies the mix duration in seconds used to mix out the previous animation and mix in the "empty" animation.

The first parameter to addEmptyAnimation() specifies the track. The second parameter specifies the mix duration. The third parameter is the delay in seconds, after which the empty animation should replace the previous animation on the track via mixing.

All animations on a track can be cleared immediately via AnimationState.clearTrack(). To clear all tracks at once, AnimationState.clearTracks() can be used. This will leave the skeleton in the last pose it was in.

To reset the pose of a skeleton to the setup pose, use Skeleton.setToSetupPose():

Swift
controller.skeleton.setToSetupPose()

This will reset both the bones and slots to their setup pose configuration. Use Skeleton.setSlotsToSetupPose() to only reset the slots to their setup pose configuration.

AnimationState Events

An AnimationState emits events during the life-cycle of an animation that is being played back. You can listen for this events to react as needed. The Spine Runtimes API defines the following EventType types:

  • SPINE_EVENT_TYPE_START: emitted when an animation is started.
  • SPINE_EVENT_TYPE_INTERRUPT: emitted when an animation's track was cleared, or a new animation was set.
  • SPINE_EVENT_TYPE_COMPLETE: emitted when an animation completes a loop.
  • SPINE_EVENT_TYPE_END: emitted when an animation will never be applied again.
  • SPINE_EVENT_TYPE_DISPOSE: emitted when the animation's track entry is disposed.
  • SPINE_EVENT_TYPE_EVENT: emitted when a user defined event happened.

To receive events, you can register an AnimationStateListener callback with either the AnimationStateWrapper to receive events across all animations, or with the TrackEntry of a specific animation queued for playback via AnimationStateWrapper.setTrackEntryListener():

Swift
var walkEntry = controller.animationState.setAnimationByName(0, "walk", true);
controller.animationStateWrapper.setTrackEntryListener(entry: walkEntry) { type, entry, event in
   if let eventk, type == SPINE_EVENT_TYPE_EVENT {
      print("User defined event: \(event.data.name ?? "--")")
   }
}

controller.animationStateWrapper.setStateListener { type, entry, event in
   print("Animation state event \(type)")
}

See the AnimationStateEvents.swift example.

Skins

/img/spine-runtimes-guide/spine-ios/skins.png

Many applications and games allow users to create custom avatars out of many individual items, such as hair, eyes, pants, or accessories like earrings or bags. With Spine, this can be achived by mixing and matching skins.

You can create custom skins from other skins like this:

Swift
var data = controller.skeletonData
var skeleton = controller.skeleton
var customSkin = Skin.create(name: "custom-skin")
customSkin.addSkin(other: data.findSkin(name: "skin-base")!)
customSkin.addSkin(other: data.findSkin(name: "nose/short")!)
customSkin.addSkin(other: data.findSkin(name: "eyelids/girly")!)
customSkin.addSkin(other: data.findSkin(name: "eyes/violet")!)
customSkin.addSkin(other: data.findSkin(name: "hair/brown")!)
customSkin.addSkin(other: data.findSkin(name: "clothes/hoodie-orange")!)
customSkin.addSkin(other: data.findSkin(name: "legs/pants-jeans")!)
customSkin.addSkin(other: data.findSkin(name: "accessories/bag")!)
customSkin.addSkin(other: data.findSkin(name: "accessories/hat-red-yellow")!)
skeleton.skin = customSkin
skeleton.setToSetupPose()

Create a custom skin with the Skin.create() static function.

Next, fetch the SkeletonData from the controller. It is used to look up skins by name via SkeletonData.findSkin().

Add all the skins you want to combine into the new custom skin via Skin.addSkin().

Finally, set the new skin on the Skeleton and call Skeleton.setSlotsToSetupPose() to ensure no attachments from previous skins and/or animations are left over.

Note: A Skin wraps an underlying C++ object. It needs to be manually disposed via a call to Skin.dispose() when it is no longer in use.

See the DressUp.swift example, which also demonstrate how to render thumbnail previews of skins using SkeletonDrawableWrapper.

Setting Bone Transforms

/img/spine-runtimes-guide/spine-ios/bone-transform.png

When authoring a skeleton in the Spine Editor, the skeleton is defined in what is called the skeleton coordinate system. This coordinate system may not align with the coordinate system of the SpineView the skeleton is rendered by. Touch coordinates relative to the SpineView need thus be converted to the skeleton coordinate system, e.g. if a user should be able to move a bone by touch.

The SpineController offers the method toSkeletonCoordinates() which takes an position CGPoint relative to the SpineView it is associated with, and converts it to the skeleton's coordinate system.

See the IKFollowing.swift example.

You can also transform coordinates into the other direction using fromSkeletonCoordinates(). See the DebugRendering.swift example to learn more.

Spine Runtimes API access

Spine iOS maps almost all of the Spine Runtime API to Swift. Objects returned by SpineController or SkeletonDrawableWrapper/SkeletonDrawable, like Skeleton or AnimationState are 1:1 translations of the spine-cpp API to Swift. You can thus apply almost all of the materials in the generic Spine Runtimes Guide to your Swift code.

Due to the nature of the spine-cpp bridge, there are however a few limitations:

  • Any returned array or map is a copy of the internal array. Modification will not have an effect.
  • You can not create, add or remove bones, slots, and other Spine objects directly.
  • The C++ class hierarchies of timelines are not exposed in Swift.