Global configuration options for rendering engines, color spaces, performance tuning, and platform-specific optimizations in Lottie iOS.
Central configuration system providing global settings for animation rendering, decoding, and behavior across all Lottie components.
/**
* Global configuration for Lottie animation system
* Controls rendering, decoding, and performance behavior
*/
public struct LottieConfiguration {
/** Shared global configuration instance */
public static var shared: LottieConfiguration { get set }
/** Rendering engine selection and fallback behavior */
public var renderingEngine: RenderingEngineOption { get set }
/** Animation data decoding strategy */
public var decodingStrategy: DecodingStrategy { get set }
/** Color space for rendering operations */
public var colorSpace: CGColorSpace { get set }
/** Reduced motion accessibility support */
public var reducedMotionOption: ReducedMotionOption { get set }
/**
* Initialize configuration with custom settings
* @param renderingEngine - Rendering engine preference
* @param decodingStrategy - JSON decoding implementation
* @param colorSpace - Color space for rendering
* @param reducedMotionOption - Reduced motion behavior
*/
public init(
renderingEngine: RenderingEngineOption = .automatic,
decodingStrategy: DecodingStrategy = .dictionaryBased,
colorSpace: CGColorSpace = CGColorSpace(name: CGColorSpace.sRGB)!,
reducedMotionOption: ReducedMotionOption = .autoDetect
)
}Usage Examples:
import Lottie
class ConfigurationExamples {
func setupGlobalConfiguration() {
// Configure global settings
LottieConfiguration.shared = LottieConfiguration(
renderingEngine: .coreAnimation,
decodingStrategy: .dictionaryBased,
colorSpace: CGColorSpace(name: CGColorSpace.displayP3)!,
reducedMotionOption: .respectReducedMotion
)
// Or modify individual properties
LottieConfiguration.shared.renderingEngine = .mainThread
LottieConfiguration.shared.reducedMotionOption = .disableAnimation
}
func useCustomConfiguration() {
// Create custom configuration for specific animation
let customConfig = LottieConfiguration(
renderingEngine: .specific(.coreAnimation),
decodingStrategy: .legacyCodable,
colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!
)
let animationView = LottieAnimationView(
animation: LottieAnimation.named("complex"),
configuration: customConfig
)
}
}Rendering engine selection system with automatic fallback and explicit engine specification for different performance profiles.
/**
* Rendering engine selection with fallback options
* Controls which rendering implementation to use
*/
public enum RenderingEngineOption: Hashable {
/** Automatic engine selection (Core Animation with Main Thread fallback) */
case automatic
/** Use specific rendering engine */
case specific(RenderingEngine)
/** Convenience accessor for Main Thread engine */
public static var mainThread: RenderingEngineOption { .specific(.mainThread) }
/** Convenience accessor for Core Animation engine */
public static var coreAnimation: RenderingEngineOption { .specific(.coreAnimation) }
}
/**
* Available rendering engines
* Each engine has different performance characteristics
*/
public enum RenderingEngine: String, Hashable, CaseIterable {
/** Main Thread rendering engine - CPU-based, high compatibility */
case mainThread = "Main Thread"
/** Core Animation rendering engine - GPU-accelerated, better performance */
case coreAnimation = "Core Animation"
}Performance Characteristics:
import Lottie
class RenderingEngineGuide {
func chooseRenderingEngine() {
// Core Animation (Recommended for most use cases)
// - GPU-accelerated rendering
// - Better performance for complex animations
// - Lower CPU usage
// - Supports most Lottie features
let coreAnimationConfig = LottieConfiguration(renderingEngine: .coreAnimation)
// Main Thread (Fallback option)
// - CPU-based rendering
// - 100% Lottie feature compatibility
// - Better for simple animations on older devices
// - More predictable behavior
let mainThreadConfig = LottieConfiguration(renderingEngine: .mainThread)
// Automatic (Default behavior)
// - Tries Core Animation first
// - Falls back to Main Thread if needed
// - Best balance of performance and compatibility
let automaticConfig = LottieConfiguration(renderingEngine: .automatic)
}
func configureForPerformance() {
// High performance configuration
let performanceConfig = LottieConfiguration(
renderingEngine: .coreAnimation,
decodingStrategy: .dictionaryBased, // Faster decoding
colorSpace: CGColorSpace(name: CGColorSpace.sRGB)! // Standard color space
)
// High compatibility configuration
let compatibilityConfig = LottieConfiguration(
renderingEngine: .mainThread,
decodingStrategy: .legacyCodable, // More compatible decoding
colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!
)
}
}Animation data decoding strategy selection controlling how JSON animation data is parsed and processed.
/**
* Strategy for decoding animation JSON data
* Controls parsing implementation and performance characteristics
*/
public enum DecodingStrategy: Hashable {
/**
* Dictionary-based decoding (Default)
* - Faster parsing performance
* - Lower memory usage during decoding
* - Recommended for most use cases
*/
case dictionaryBased
/**
* Legacy Codable decoding
* - Uses Swift's Codable protocol
* - More thorough type checking
* - Better compatibility with edge cases
* - Slower but more robust
*/
case legacyCodable
}Usage Examples:
import Lottie
class DecodingStrategyExamples {
func compareDecodingStrategies() {
// Fast decoding for performance-critical use cases
let fastConfig = LottieConfiguration(decodingStrategy: .dictionaryBased)
// Robust decoding for complex animations
let robustConfig = LottieConfiguration(decodingStrategy: .legacyCodable)
// Load animation with specific strategy
do {
let animationData = try Data(contentsOf: animationURL)
let animation = try LottieAnimation.from(
data: animationData,
strategy: .dictionaryBased
)
} catch {
print("Decoding failed: \(error)")
// Fallback to legacy decoding
let fallbackAnimation = try? LottieAnimation.from(
data: animationData,
strategy: .legacyCodable
)
}
}
func handleDecodingErrors() {
func loadAnimationWithFallback(data: Data) -> LottieAnimation? {
// Try fast decoding first
if let animation = try? LottieAnimation.from(data: data, strategy: .dictionaryBased) {
return animation
}
// Fall back to legacy decoding
if let animation = try? LottieAnimation.from(data: data, strategy: .legacyCodable) {
return animation
}
return nil
}
}
}Accessibility configuration for reduced motion support, respecting user preferences and providing animation alternatives.
/**
* Reduced motion accessibility configuration
* Controls animation behavior based on system accessibility settings
*/
public enum ReducedMotionOption: Hashable {
/**
* Automatically detect reduced motion preference
* Respects UIAccessibility.isReduceMotionEnabled
*/
case autoDetect
/**
* Always respect reduced motion setting
* Disables or simplifies animations when reduced motion is enabled
*/
case respectReducedMotion
/**
* Disable animation entirely for reduced motion
* Shows final frame when reduced motion is active
*/
case disableAnimation
/**
* Ignore reduced motion preference
* Always plays full animations regardless of setting
*/
case ignoreReducedMotion
}Usage Examples:
import Lottie
import UIKit
class ReducedMotionExamples {
func setupReducedMotionSupport() {
// Respect system reduced motion preference
LottieConfiguration.shared.reducedMotionOption = .respectReducedMotion
// Check current reduced motion state
let isReducedMotionEnabled = UIAccessibility.isReduceMotionEnabled
print("Reduced motion enabled: \(isReducedMotionEnabled)")
// Configure different behaviors
let respectfulConfig = LottieConfiguration(reducedMotionOption: .respectReducedMotion)
let disabledConfig = LottieConfiguration(reducedMotionOption: .disableAnimation)
let ignoredConfig = LottieConfiguration(reducedMotionOption: .ignoreReducedMotion)
}
func handleReducedMotionChanges() {
// Listen for reduced motion changes
NotificationCenter.default.addObserver(
forName: UIAccessibility.reduceMotionStatusDidChangeNotification,
object: nil,
queue: .main
) { _ in
self.updateAnimationsForReducedMotion()
}
}
func updateAnimationsForReducedMotion() {
if UIAccessibility.isReduceMotionEnabled {
// Update configuration to respect reduced motion
LottieConfiguration.shared.reducedMotionOption = .disableAnimation
// Or provide alternative static content
showStaticAlternative()
} else {
// Re-enable full animations
LottieConfiguration.shared.reducedMotionOption = .ignoreReducedMotion
restoreAnimations()
}
}
func showStaticAlternative() {
// Implementation would show static images or simplified animations
}
func restoreAnimations() {
// Implementation would restore full animations
}
}Color space configuration for accurate color reproduction across different display technologies and color gamuts.
/**
* Color space configuration for accurate rendering
*/
extension LottieConfiguration {
/**
* Configure for standard sRGB color space
* Recommended for most applications
*/
public static func sRGBConfiguration() -> LottieConfiguration {
return LottieConfiguration(
colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!
)
}
/**
* Configure for Display P3 wide color gamut
* Recommended for content targeting newer devices
*/
public static func displayP3Configuration() -> LottieConfiguration {
return LottieConfiguration(
colorSpace: CGColorSpace(name: CGColorSpace.displayP3)!
)
}
/**
* Configure for Adobe RGB color space
* For professional content workflows
*/
public static func adobeRGBConfiguration() -> LottieConfiguration {
return LottieConfiguration(
colorSpace: CGColorSpace(name: CGColorSpace.adobeRGB1998)!
)
}
}Usage Examples:
import Lottie
class ColorSpaceConfiguration {
func setupColorSpaces() {
// Standard sRGB for broad compatibility
let standardConfig = LottieConfiguration.sRGBConfiguration()
// Wide color gamut for modern devices
let wideColorConfig = LottieConfiguration.displayP3Configuration()
// Check device capabilities
if let mainScreen = UIScreen.main.traitCollection.displayGamut == .P3 {
LottieConfiguration.shared = wideColorConfig
} else {
LottieConfiguration.shared = standardConfig
}
// Custom color space configuration
let customColorSpace = CGColorSpace(name: CGColorSpace.genericRGBLinear)!
let customConfig = LottieConfiguration(colorSpace: customColorSpace)
}
func adaptToDevice() {
// Adapt color space to device capabilities
let traitCollection = UITraitCollection.current
switch traitCollection.displayGamut {
case .P3:
LottieConfiguration.shared.colorSpace = CGColorSpace(name: CGColorSpace.displayP3)!
case .sRGB:
LottieConfiguration.shared.colorSpace = CGColorSpace(name: CGColorSpace.sRGB)!
default:
LottieConfiguration.shared.colorSpace = CGColorSpace(name: CGColorSpace.sRGB)!
}
}
}Advanced configuration patterns for optimizing performance in different scenarios and device capabilities.
/**
* Performance optimization configurations
*/
extension LottieConfiguration {
/**
* Configuration optimized for battery life
* Reduces power consumption at cost of some visual quality
*/
public static func batteryOptimizedConfiguration() -> LottieConfiguration {
return LottieConfiguration(
renderingEngine: .mainThread, // Lower GPU usage
decodingStrategy: .dictionaryBased, // Faster decoding
colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!, // Standard color space
reducedMotionOption: .autoDetect // Respect user preferences
)
}
/**
* Configuration optimized for performance
* Maximum rendering performance for smooth animations
*/
public static func performanceOptimizedConfiguration() -> LottieConfiguration {
return LottieConfiguration(
renderingEngine: .coreAnimation, // GPU acceleration
decodingStrategy: .dictionaryBased, // Fast decoding
colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!, // Efficient color space
reducedMotionOption: .ignoreReducedMotion // Full animations
)
}
/**
* Configuration optimized for quality
* Best visual quality and color accuracy
*/
public static func qualityOptimizedConfiguration() -> LottieConfiguration {
return LottieConfiguration(
renderingEngine: .automatic, // Best available engine
decodingStrategy: .legacyCodable, // More thorough decoding
colorSpace: CGColorSpace(name: CGColorSpace.displayP3)!, // Wide color gamut
reducedMotionOption: .respectReducedMotion // Accessibility support
)
}
}Usage Examples:
import Lottie
class PerformanceConfiguration {
func setupForDevice() {
// Detect device capabilities and configure accordingly
let deviceModel = UIDevice.current.model
let processorCount = ProcessInfo.processInfo.processorCount
let memorySize = ProcessInfo.processInfo.physicalMemory
if processorCount >= 6 && memorySize > 3_000_000_000 { // High-end device
LottieConfiguration.shared = .performanceOptimizedConfiguration()
} else if memorySize < 2_000_000_000 { // Lower-end device
LottieConfiguration.shared = .batteryOptimizedConfiguration()
} else {
LottieConfiguration.shared = .qualityOptimizedConfiguration()
}
}
func adaptToApplicationState() {
// Monitor application state for performance optimization
NotificationCenter.default.addObserver(
forName: UIApplication.didEnterBackgroundNotification,
object: nil,
queue: .main
) { _ in
// Switch to battery-optimized mode when backgrounded
LottieConfiguration.shared = .batteryOptimizedConfiguration()
}
NotificationCenter.default.addObserver(
forName: UIApplication.willEnterForegroundNotification,
object: nil,
queue: .main
) { _ in
// Restore performance mode when foregrounded
LottieConfiguration.shared = .performanceOptimizedConfiguration()
}
}
func monitorPerformance() {
// Monitor frame rate and adjust configuration
let displayLink = CADisplayLink(target: self, selector: #selector(frameUpdate))
displayLink.add(to: .main, forMode: .common)
var frameCount = 0
var lastTimestamp = CACurrentMediaTime()
// Implementation would track FPS and adjust configuration
}
@objc func frameUpdate(displayLink: CADisplayLink) {
// Track performance metrics and adjust configuration as needed
let currentTime = CACurrentMediaTime()
// Implementation for performance monitoring
}
}Configuration options for debugging, development, and profiling Lottie animations.
/**
* Development and debugging configuration helpers
*/
extension LottieConfiguration {
/**
* Configuration for development with enhanced debugging
*/
public static func developmentConfiguration() -> LottieConfiguration {
return LottieConfiguration(
renderingEngine: .automatic, // Test both engines
decodingStrategy: .legacyCodable, // More error checking
colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!,
reducedMotionOption: .ignoreReducedMotion // Always show animations
)
}
/**
* Configuration for performance profiling
*/
public static func profilingConfiguration() -> LottieConfiguration {
return LottieConfiguration(
renderingEngine: .coreAnimation, // Consistent GPU profiling
decodingStrategy: .dictionaryBased, // Minimize parsing overhead
colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!,
reducedMotionOption: .ignoreReducedMotion // Consistent timing
)
}
}Usage Examples:
import Lottie
class DebugConfiguration {
func setupForDevelopment() {
#if DEBUG
LottieConfiguration.shared = .developmentConfiguration()
// Enable detailed logging
LottieLogger.shared = .printToConsole
// Test different configurations
testConfigurations()
#else
LottieConfiguration.shared = .performanceOptimizedConfiguration()
#endif
}
func testConfigurations() {
let configs = [
("Core Animation", LottieConfiguration(renderingEngine: .coreAnimation)),
("Main Thread", LottieConfiguration(renderingEngine: .mainThread)),
("Dictionary Decoding", LottieConfiguration(decodingStrategy: .dictionaryBased)),
("Codable Decoding", LottieConfiguration(decodingStrategy: .legacyCodable))
]
for (name, config) in configs {
print("Testing configuration: \(name)")
testAnimationWithConfig(config)
}
}
func testAnimationWithConfig(_ config: LottieConfiguration) {
let animationView = LottieAnimationView(configuration: config)
animationView.animation = LottieAnimation.named("test_animation")
let startTime = CACurrentMediaTime()
animationView.play { finished in
let duration = CACurrentMediaTime() - startTime
print("Animation completed in \(duration)s, finished: \(finished)")
}
}
}