code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
//
// KeyframeGroup.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/14/19.
//
// MARK: - KeyframeGroup
/// Used for coding/decoding a group of Keyframes by type.
///
/// Keyframe data is wrapped in a dictionary { "k" : KeyframeData }.
/// The keyframe data can either be an array of keyframes or, if no animation is present, the raw value.
/// This helper object is needed to properly decode the json.
final class KeyframeGroup<T> {
// MARK: Lifecycle
init(
keyframes: ContiguousArray<Keyframe<T>>,
unsupportedAfterEffectsExpression: String? = nil)
{
self.keyframes = keyframes
self.unsupportedAfterEffectsExpression = unsupportedAfterEffectsExpression
}
init(
_ value: T,
unsupportedAfterEffectsExpression: String? = nil)
{
keyframes = [Keyframe(value)]
self.unsupportedAfterEffectsExpression = unsupportedAfterEffectsExpression
}
// MARK: Internal
enum KeyframeWrapperKey: String, CodingKey {
case keyframeData = "k"
case unsupportedAfterEffectsExpression = "x"
}
let keyframes: ContiguousArray<Keyframe<T>>
/// lottie-ios doesn't support After Effects expressions, but we parse them so we can log diagnostics.
/// More info: https://helpx.adobe.com/after-effects/using/expression-basics.html
let unsupportedAfterEffectsExpression: String?
}
// MARK: Decodable
extension KeyframeGroup: Decodable where T: Decodable {
convenience init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: KeyframeWrapperKey.self)
let unsupportedAfterEffectsExpression = try? container.decode(String.self, forKey: .unsupportedAfterEffectsExpression)
if let keyframeData: T = try? container.decode(T.self, forKey: .keyframeData) {
/// Try to decode raw value; No keyframe data.
self.init(
keyframes: [Keyframe<T>(keyframeData)],
unsupportedAfterEffectsExpression: unsupportedAfterEffectsExpression)
} else {
// Decode and array of keyframes.
//
// Body Movin and Lottie deal with keyframes in different ways.
//
// A keyframe object in Body movin defines a span of time with a START
// and an END, from the current keyframe time to the next keyframe time.
//
// A keyframe object in Lottie defines a singular point in time/space.
// This point has an in-tangent and an out-tangent.
//
// To properly decode this we must iterate through keyframes while holding
// reference to the previous keyframe.
var keyframesContainer = try container.nestedUnkeyedContainer(forKey: .keyframeData)
var keyframes = ContiguousArray<Keyframe<T>>()
var previousKeyframeData: KeyframeData<T>?
while !keyframesContainer.isAtEnd {
// Ensure that Time and Value are present.
let keyframeData = try keyframesContainer.decode(KeyframeData<T>.self)
guard
let value: T = keyframeData.startValue ?? previousKeyframeData?.endValue,
let time = keyframeData.time
else {
/// Missing keyframe data. JSON must be corrupt.
throw DecodingError.dataCorruptedError(
forKey: KeyframeWrapperKey.keyframeData,
in: container,
debugDescription: "Missing keyframe data.")
}
keyframes.append(Keyframe<T>(
value: value,
time: AnimationFrameTime(time),
isHold: keyframeData.isHold,
inTangent: previousKeyframeData?.inTangent,
outTangent: keyframeData.outTangent,
spatialInTangent: previousKeyframeData?.spatialInTangent,
spatialOutTangent: keyframeData.spatialOutTangent))
previousKeyframeData = keyframeData
}
self.init(
keyframes: keyframes,
unsupportedAfterEffectsExpression: unsupportedAfterEffectsExpression)
}
}
}
// MARK: Encodable
extension KeyframeGroup: Encodable where T: Encodable {
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: KeyframeWrapperKey.self)
if keyframes.count == 1 {
let keyframe = keyframes[0]
try container.encode(keyframe.value, forKey: .keyframeData)
} else {
var keyframeContainer = container.nestedUnkeyedContainer(forKey: .keyframeData)
for i in 1..<keyframes.endIndex {
let keyframe = keyframes[i - 1]
let nextKeyframe = keyframes[i]
let keyframeData = KeyframeData<T>(
startValue: keyframe.value,
endValue: nextKeyframe.value,
time: keyframe.time,
hold: keyframe.isHold ? 1 : nil,
inTangent: nextKeyframe.inTangent,
outTangent: keyframe.outTangent,
spatialInTangent: nil,
spatialOutTangent: nil)
try keyframeContainer.encode(keyframeData)
}
}
}
}
// MARK: DictionaryInitializable
extension KeyframeGroup: DictionaryInitializable where T: AnyInitializable {
convenience init(dictionary: [String: Any]) throws {
var keyframes = ContiguousArray<Keyframe<T>>()
let unsupportedAfterEffectsExpression = dictionary[KeyframeWrapperKey.unsupportedAfterEffectsExpression.rawValue] as? String
if
let rawValue = dictionary[KeyframeWrapperKey.keyframeData.rawValue],
let value = try? T(value: rawValue)
{
keyframes = [Keyframe<T>(value)]
} else {
var frameDictionaries: [[String: Any]]
if let singleFrameDictionary = dictionary[KeyframeWrapperKey.keyframeData.rawValue] as? [String: Any] {
frameDictionaries = [singleFrameDictionary]
} else {
frameDictionaries = try dictionary.value(for: KeyframeWrapperKey.keyframeData)
}
var previousKeyframeData: KeyframeData<T>?
for frameDictionary in frameDictionaries {
let data = try KeyframeData<T>(dictionary: frameDictionary)
guard
let value: T = data.startValue ?? previousKeyframeData?.endValue,
let time = data.time
else {
throw InitializableError.invalidInput()
}
keyframes.append(Keyframe<T>(
value: value,
time: time,
isHold: data.isHold,
inTangent: previousKeyframeData?.inTangent,
outTangent: data.outTangent,
spatialInTangent: previousKeyframeData?.spatialInTangent,
spatialOutTangent: data.spatialOutTangent))
previousKeyframeData = data
}
}
self.init(
keyframes: keyframes,
unsupportedAfterEffectsExpression: unsupportedAfterEffectsExpression)
}
}
// MARK: Equatable
extension KeyframeGroup: Equatable where T: Equatable {
static func == (_ lhs: KeyframeGroup<T>, _ rhs: KeyframeGroup<T>) -> Bool {
lhs.keyframes == rhs.keyframes
}
}
// MARK: Hashable
extension KeyframeGroup: Hashable where T: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(keyframes)
}
}
// MARK: Sendable
extension KeyframeGroup: Sendable where T: Sendable { }
extension Keyframe {
/// Creates a copy of this `Keyframe` with the same timing data, but a different value
func withValue<Value>(_ newValue: Value) -> Keyframe<Value> {
Keyframe<Value>(
value: newValue,
time: time,
isHold: isHold,
inTangent: inTangent,
outTangent: outTangent,
spatialInTangent: spatialInTangent,
spatialOutTangent: spatialOutTangent)
}
}
extension KeyframeGroup {
/// Maps the values of each individual keyframe in this group
func map<NewValue>(_ transformation: (T) throws -> NewValue) rethrows -> KeyframeGroup<NewValue> {
KeyframeGroup<NewValue>(
keyframes: ContiguousArray(try keyframes.map { keyframe in
keyframe.withValue(try transformation(keyframe.value))
}),
unsupportedAfterEffectsExpression: unsupportedAfterEffectsExpression)
}
}
// MARK: - AnyKeyframeGroup
/// A type-erased wrapper for `KeyframeGroup`s
protocol AnyKeyframeGroup {
/// An untyped copy of these keyframes
var untyped: KeyframeGroup<Any> { get }
/// An untyped `KeyframeInterpolator` for these keyframes
var interpolator: AnyValueProvider { get }
}
// MARK: - KeyframeGroup + AnyKeyframeGroup
extension KeyframeGroup: AnyKeyframeGroup where T: AnyInterpolatable {
var untyped: KeyframeGroup<Any> {
map { $0 as Any }
}
var interpolator: AnyValueProvider {
KeyframeInterpolator(keyframes: keyframes)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Keyframes/KeyframeGroup.swift
|
Swift
|
unknown
| 8,381
|
// Created by Cal Stephens on 8/14/23.
// Copyright © 2023 Airbnb Inc. All rights reserved.
final class DropShadowEffect: LayerEffect {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The color of the drop shadow
var color: ColorEffectValue? {
value(named: "Shadow Color")
}
/// Opacity between 0 and 255
var opacity: Vector1DEffectValue? {
value(named: "Opacity")
}
/// The direction / angle of the drop shadow, in degrees
var direction: Vector1DEffectValue? {
value(named: "Direction")
}
/// The distance of the drop shadow
var distance: Vector1DEffectValue? {
value(named: "Distance")
}
/// The softness of the drop shadow
var softness: Vector1DEffectValue? {
value(named: "Softness")
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/LayerEffects/DropShadowEffect.swift
|
Swift
|
unknown
| 936
|
// Created by Cal Stephens on 8/14/23.
// Copyright © 2023 Airbnb Inc. All rights reserved.
final class ColorEffectValue: EffectValue {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
value = try? container.decode(KeyframeGroup<LottieColor>.self, forKey: .value)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
let valueDictionary: [String: Any] = try dictionary.value(for: CodingKeys.value)
value = try KeyframeGroup<LottieColor>(dictionary: valueDictionary)
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The value of the color
let value: KeyframeGroup<LottieColor>?
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(value, forKey: .value)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case value = "v"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/LayerEffects/EffectValues/ColorEffectValue.swift
|
Swift
|
unknown
| 1,046
|
// Created by Cal Stephens on 8/15/23.
// Copyright © 2023 Airbnb Inc. All rights reserved.
// MARK: - EffectValueType
/// https://lottiefiles.github.io/lottie-docs/schema/#/$defs/effect-values
enum EffectValueType: Int, Codable, Sendable {
case slider = 0
case angle = 1
case color = 2
case unknown = 9999
init(from decoder: Decoder) throws {
self = try EffectValueType(rawValue: decoder.singleValueContainer().decode(RawValue.self)) ?? .unknown
}
}
// MARK: ClassFamily
extension EffectValueType: ClassFamily {
static var discriminator: Discriminator = .type
func getType() -> AnyObject.Type {
switch self {
case .slider:
return Vector1DEffectValue.self
case .angle:
return Vector1DEffectValue.self
case .color:
return ColorEffectValue.self
case .unknown:
// Unsupported
return LayerEffect.self
}
}
}
// MARK: - EffectValue
class EffectValue: Codable, DictionaryInitializable {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: EffectValue.CodingKeys.self)
type = try container.decode(EffectValueType.self, forKey: .type)
name = try container.decode(String.self, forKey: .name)
}
required init(dictionary: [String: Any]) throws {
type = (try? dictionary.value(for: CodingKeys.type)).flatMap(EffectValueType.init(rawValue:)) ?? .unknown
name = (try? dictionary.value(for: CodingKeys.name)) ?? "Effect"
}
// MARK: Internal
/// The type of effect value
let type: EffectValueType
/// The name of the effect value
let name: String
// MARK: Fileprivate
fileprivate enum CodingKeys: String, CodingKey {
case type = "ty"
case name = "nm"
}
}
extension [EffectValue] {
static func fromDictionaries(_ dictionaries: [[String: Any]]) throws -> [EffectValue] {
try dictionaries.compactMap { dictionary in
let shapeType = dictionary[EffectValue.CodingKeys.type.rawValue] as? Int
switch EffectValueType(rawValue: shapeType ?? EffectValueType.unknown.rawValue) {
case .slider:
return try Vector1DEffectValue(dictionary: dictionary)
case .angle:
return try Vector1DEffectValue(dictionary: dictionary)
case .color:
return try ColorEffectValue(dictionary: dictionary)
case .unknown:
// Unsupported
return try EffectValue(dictionary: dictionary)
case nil:
return nil
}
}
}
}
// MARK: - EffectValue + Sendable
/// Since `EffectValue` isn't `final`, we have to use `@unchecked Sendable` instead of `Sendable.`
/// All `EffectValue` subclasses are immutable `Sendable` values.
// swiftlint:disable:next no_unchecked_sendable
extension EffectValue: @unchecked Sendable { }
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/LayerEffects/EffectValues/EffectValue.swift
|
Swift
|
unknown
| 2,771
|
// Created by Cal Stephens on 8/14/23.
// Copyright © 2023 Airbnb Inc. All rights reserved.
final class Vector1DEffectValue: EffectValue {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
value = try? container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .value)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
let valueDictionary: [String: Any] = try dictionary.value(for: CodingKeys.value)
value = try KeyframeGroup<LottieVector1D>(dictionary: valueDictionary)
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The value of the slider
let value: KeyframeGroup<LottieVector1D>?
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(value, forKey: .value)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case value = "v"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/LayerEffects/EffectValues/Vector1DEffectValue.swift
|
Swift
|
unknown
| 1,059
|
// Created by Cal Stephens on 8/14/23.
// Copyright © 2023 Airbnb Inc. All rights reserved.
// MARK: - LayerEffectType
/// https://lottiefiles.github.io/lottie-docs/schema/#/$defs/effects
enum LayerEffectType: Int, Codable, Sendable {
case dropShadow = 25
case unknown = 9999
init(from decoder: Decoder) throws {
self = try LayerEffectType(rawValue: decoder.singleValueContainer().decode(RawValue.self)) ?? .unknown
}
}
// MARK: ClassFamily
extension LayerEffectType: ClassFamily {
static var discriminator: Discriminator = .type
func getType() -> AnyObject.Type {
switch self {
case .dropShadow:
return DropShadowEffect.self
case .unknown:
// Unsupported
return LayerEffect.self
}
}
}
// MARK: - LayerEffect
class LayerEffect: Codable, DictionaryInitializable {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: LayerEffect.CodingKeys.self)
name = try container.decodeIfPresent(String.self, forKey: .name) ?? "Effect"
type = try container.decode(LayerEffectType.self, forKey: .type)
effects = try container.decodeIfPresent([EffectValue].self, ofFamily: EffectValueType.self, forKey: .effects) ?? []
}
required init(dictionary: [String: Any]) throws {
name = (try? dictionary.value(for: CodingKeys.name)) ?? "Layer"
type = LayerEffectType(rawValue: try dictionary.value(for: CodingKeys.type)) ?? .unknown
if let valueDictionaries = dictionary[CodingKeys.effects.rawValue] as? [[String: Any]] {
effects = try [EffectValue].fromDictionaries(valueDictionaries)
} else {
effects = []
}
}
// MARK: Internal
/// The name of the effect
let name: String
/// The type of effect
let type: LayerEffectType
/// Values that configure the behavior of the effect
let effects: [EffectValue]
/// Retrieves the `EffectValue` for the given name
func value<ValueType: EffectValue>(named name: String) -> ValueType? {
effects.first(where: {
$0.name == name && $0 is ValueType
}) as? ValueType
}
// MARK: Fileprivate
fileprivate enum CodingKeys: String, CodingKey {
case name = "nm"
case type = "ty"
case effects = "ef"
}
}
extension [LayerEffect] {
static func fromDictionaries(_ dictionaries: [[String: Any]]) throws -> [LayerEffect] {
try dictionaries.compactMap { dictionary in
let shapeType = dictionary[LayerEffect.CodingKeys.type.rawValue] as? Int
switch LayerEffectType(rawValue: shapeType ?? LayerEffectType.unknown.rawValue) {
case .dropShadow:
return try DropShadowEffect(dictionary: dictionary)
case .unknown, nil:
// Unsupported
return try LayerEffect(dictionary: dictionary)
}
}
}
}
// MARK: - LayerEffect + Sendable
/// Since `LayerEffect` isn't `final`, we have to use `@unchecked Sendable` instead of `Sendable.`
/// All `LayerEffect` subclasses are immutable `Sendable` values.
// swiftlint:disable:next no_unchecked_sendable
extension LayerEffect: @unchecked Sendable { }
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/LayerEffects/LayerEffect.swift
|
Swift
|
unknown
| 3,081
|
// Created by Cal Stephens on 8/14/23.
// Copyright © 2023 Airbnb Inc. All rights reserved.
final class DropShadowStyle: LayerStyle {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: DropShadowStyle.CodingKeys.self)
opacity = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .opacity)
color = try container.decode(KeyframeGroup<LottieColor>.self, forKey: .color)
angle = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .angle)
size = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .size)
distance = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .distance)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
let opacityDictionary: [String: Any] = try dictionary.value(for: CodingKeys.opacity)
opacity = try KeyframeGroup<LottieVector1D>(dictionary: opacityDictionary)
let colorDictionary: [String: Any] = try dictionary.value(for: CodingKeys.color)
color = try KeyframeGroup<LottieColor>(dictionary: colorDictionary)
let angleDictionary: [String: Any] = try dictionary.value(for: CodingKeys.angle)
angle = try KeyframeGroup<LottieVector1D>(dictionary: angleDictionary)
let sizeDictionary: [String: Any] = try dictionary.value(for: CodingKeys.size)
size = try KeyframeGroup<LottieVector1D>(dictionary: sizeDictionary)
let distanceDictionary: [String: Any] = try dictionary.value(for: CodingKeys.distance)
distance = try KeyframeGroup<LottieVector1D>(dictionary: distanceDictionary)
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The opacity of the drop shadow
let opacity: KeyframeGroup<LottieVector1D>
/// The color of the drop shadow
let color: KeyframeGroup<LottieColor>
/// The angle of the drop shadow, in degrees,
/// with `0` representing a shadow straight-down from the layer
/// (`offsetY=distance, offsetX=0`).
let angle: KeyframeGroup<LottieVector1D>
/// The size of the drop shadow
let size: KeyframeGroup<LottieVector1D>
/// The distance of the drop shadow
let distance: KeyframeGroup<LottieVector1D>
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(opacity, forKey: .opacity)
try container.encode(color, forKey: .color)
try container.encode(angle, forKey: .angle)
try container.encode(size, forKey: .size)
try container.encode(distance, forKey: .distance)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case color = "c"
case opacity = "o"
case angle = "a"
case size = "s"
case distance = "d"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/LayerStyles/DropShadowStyle.swift
|
Swift
|
unknown
| 2,798
|
// Created by Cal Stephens on 8/14/23.
// Copyright © 2023 Airbnb Inc. All rights reserved.
// MARK: - LayerStyleType
enum LayerStyleType: Int, Codable, Sendable {
case dropShadow = 1
case unknown = 9999
init(from decoder: Decoder) throws {
self = try LayerStyleType(rawValue: decoder.singleValueContainer().decode(RawValue.self)) ?? .unknown
}
}
// MARK: ClassFamily
extension LayerStyleType: ClassFamily {
static var discriminator: Discriminator = .type
func getType() -> AnyObject.Type {
switch self {
case .dropShadow:
return DropShadowStyle.self
case .unknown:
// Unsupported
return LayerStyle.self
}
}
}
// MARK: - LayerStyle
class LayerStyle: Codable, DictionaryInitializable {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: LayerStyle.CodingKeys.self)
name = try container.decodeIfPresent(String.self, forKey: .name) ?? "Style"
type = try container.decode(LayerStyleType.self, forKey: .type)
}
required init(dictionary: [String: Any]) throws {
name = (try? dictionary.value(for: CodingKeys.name)) ?? "Layer"
type = LayerStyleType(rawValue: try dictionary.value(for: CodingKeys.type)) ?? .unknown
}
// MARK: Internal
/// The name of the style
let name: String
/// The type of style
let type: LayerStyleType
// MARK: Fileprivate
fileprivate enum CodingKeys: String, CodingKey {
case name = "nm"
case type = "ty"
}
}
extension [LayerStyle] {
static func fromDictionaries(_ dictionaries: [[String: Any]]) throws -> [LayerStyle] {
try dictionaries.compactMap { dictionary in
let shapeType = dictionary[LayerStyle.CodingKeys.type.rawValue] as? Int
switch LayerStyleType(rawValue: shapeType ?? LayerStyleType.unknown.rawValue) {
case .dropShadow:
return try DropShadowStyle(dictionary: dictionary)
case .unknown, nil:
// Unsupported
return try LayerStyle(dictionary: dictionary)
}
}
}
}
// MARK: - LayerStyle + Sendable
/// Since `LayerStyle` isn't `final`, we have to use `@unchecked Sendable` instead of `Sendable.`
/// All `LayerStyle` subclasses are immutable `Sendable` values.
// swiftlint:disable:next no_unchecked_sendable
extension LayerStyle: @unchecked Sendable { }
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/LayerStyles/LayerStyle.swift
|
Swift
|
unknown
| 2,335
|
//
// ImageLayer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
/// A layer that holds an image.
final class ImageLayerModel: LayerModel {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: ImageLayerModel.CodingKeys.self)
referenceID = try container.decode(String.self, forKey: .referenceID)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
referenceID = try dictionary.value(for: CodingKeys.referenceID)
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The reference ID of the image.
let referenceID: String
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(referenceID, forKey: .referenceID)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case referenceID = "refId"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Layers/ImageLayerModel.swift
|
Swift
|
unknown
| 1,006
|
//
// Layer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/7/19.
//
// MARK: - LayerType + ClassFamily
/// Used for mapping a heterogeneous list to classes for parsing.
extension LayerType: ClassFamily {
static var discriminator: Discriminator = .type
func getType() -> AnyObject.Type {
switch self {
case .precomp:
return PreCompLayerModel.self
case .solid:
return SolidLayerModel.self
case .image:
return ImageLayerModel.self
case .null:
return LayerModel.self
case .shape:
return ShapeLayerModel.self
case .text:
return TextLayerModel.self
case .unknown:
return LayerModel.self
}
}
}
// MARK: - LayerType
public enum LayerType: Int, Codable {
case precomp
case solid
case image
case null
case shape
case text
case unknown
public init(from decoder: Decoder) throws {
self = try LayerType(rawValue: decoder.singleValueContainer().decode(RawValue.self)) ?? .null
}
}
// MARK: - MatteType
public enum MatteType: Int, Codable {
case none
case add
case invert
case unknown
}
// MARK: - BlendMode
public enum BlendMode: Int, Codable {
case normal
case multiply
case screen
case overlay
case darken
case lighten
case colorDodge
case colorBurn
case hardLight
case softLight
case difference
case exclusion
case hue
case saturation
case color
case luminosity
}
// MARK: - LayerModel
/// A base top container for shapes, images, and other view objects.
class LayerModel: Codable, DictionaryInitializable {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: LayerModel.CodingKeys.self)
name = try container.decodeIfPresent(String.self, forKey: .name) ?? "Layer"
index = try container.decodeIfPresent(Int.self, forKey: .index) ?? .random(in: Int.min...Int.max)
type = try container.decode(LayerType.self, forKey: .type)
coordinateSpace = try container.decodeIfPresent(CoordinateSpace.self, forKey: .coordinateSpace) ?? .type2d
inFrame = try container.decode(Double.self, forKey: .inFrame)
outFrame = try container.decode(Double.self, forKey: .outFrame)
startTime = try container.decode(Double.self, forKey: .startTime)
transform = try container.decodeIfPresent(Transform.self, forKey: .transform) ?? .default
parent = try container.decodeIfPresent(Int.self, forKey: .parent)
blendMode = try container.decodeIfPresent(BlendMode.self, forKey: .blendMode) ?? .normal
masks = try container.decodeIfPresent([Mask].self, forKey: .masks)
timeStretch = try container.decodeIfPresent(Double.self, forKey: .timeStretch) ?? 1
matte = try container.decodeIfPresent(MatteType.self, forKey: .matte)
hidden = try container.decodeIfPresent(Bool.self, forKey: .hidden) ?? false
styles = try container.decodeIfPresent([LayerStyle].self, ofFamily: LayerStyleType.self, forKey: .styles) ?? []
effects = try container.decodeIfPresent([LayerEffect].self, ofFamily: LayerEffectType.self, forKey: .effects) ?? []
}
required init(dictionary: [String: Any]) throws {
name = (try? dictionary.value(for: CodingKeys.name)) ?? "Layer"
index = try dictionary.value(for: CodingKeys.index) ?? .random(in: Int.min...Int.max)
type = LayerType(rawValue: try dictionary.value(for: CodingKeys.type)) ?? .null
if
let coordinateSpaceRawValue = dictionary[CodingKeys.coordinateSpace.rawValue] as? Int,
let coordinateSpace = CoordinateSpace(rawValue: coordinateSpaceRawValue)
{
self.coordinateSpace = coordinateSpace
} else {
coordinateSpace = .type2d
}
inFrame = try dictionary.value(for: CodingKeys.inFrame)
outFrame = try dictionary.value(for: CodingKeys.outFrame)
startTime = try dictionary.value(for: CodingKeys.startTime)
parent = try? dictionary.value(for: CodingKeys.parent)
if
let transformDictionary: [String: Any] = try dictionary.value(for: CodingKeys.transform),
let transform = try? Transform(dictionary: transformDictionary)
{
self.transform = transform
} else {
transform = .default
}
if
let blendModeRawValue = dictionary[CodingKeys.blendMode.rawValue] as? Int,
let blendMode = BlendMode(rawValue: blendModeRawValue)
{
self.blendMode = blendMode
} else {
blendMode = .normal
}
if let maskDictionaries = dictionary[CodingKeys.masks.rawValue] as? [[String: Any]] {
masks = try maskDictionaries.map { try Mask(dictionary: $0) }
} else {
masks = nil
}
timeStretch = (try? dictionary.value(for: CodingKeys.timeStretch)) ?? 1
if let matteRawValue = dictionary[CodingKeys.matte.rawValue] as? Int {
matte = MatteType(rawValue: matteRawValue)
} else {
matte = nil
}
hidden = (try? dictionary.value(for: CodingKeys.hidden)) ?? false
if let styleDictionaries = dictionary[CodingKeys.styles.rawValue] as? [[String: Any]] {
styles = try [LayerStyle].fromDictionaries(styleDictionaries)
} else {
styles = []
}
if let effectDictionaries = dictionary[CodingKeys.effects.rawValue] as? [[String: Any]] {
effects = try [LayerEffect].fromDictionaries(effectDictionaries)
} else {
effects = []
}
}
// MARK: Internal
/// The readable name of the layer
let name: String
/// The index of the layer
let index: Int
/// The type of the layer.
let type: LayerType
/// The coordinate space
let coordinateSpace: CoordinateSpace
/// The in time of the layer in frames.
let inFrame: Double
/// The out time of the layer in frames.
let outFrame: Double
/// The start time of the layer in frames.
let startTime: Double
/// The transform of the layer
let transform: Transform
/// The index of the parent layer, if applicable.
let parent: Int?
/// The blending mode for the layer
let blendMode: BlendMode
/// An array of masks for the layer.
let masks: [Mask]?
/// A number that stretches time by a multiplier
let timeStretch: Double
/// The type of matte if any.
let matte: MatteType?
/// Whether or not this layer is hidden, in which case it will not be rendered.
let hidden: Bool
/// A list of styles to apply to this layer
let styles: [LayerStyle]
/// A list of effects to apply to this layer
let effects: [LayerEffect]
// MARK: Fileprivate
fileprivate enum CodingKeys: String, CodingKey {
case name = "nm"
case index = "ind"
case type = "ty"
case coordinateSpace = "ddd"
case inFrame = "ip"
case outFrame = "op"
case startTime = "st"
case transform = "ks"
case parent
case blendMode = "bm"
case masks = "masksProperties"
case timeStretch = "sr"
case matte = "tt"
case hidden = "hd"
case styles = "sy"
case effects = "ef"
}
}
extension [LayerModel] {
static func fromDictionaries(_ dictionaries: [[String: Any]]) throws -> [LayerModel] {
try dictionaries.compactMap { dictionary in
let layerType = dictionary[LayerModel.CodingKeys.type.rawValue] as? Int
switch LayerType(rawValue: layerType ?? LayerType.null.rawValue) {
case .precomp:
return try PreCompLayerModel(dictionary: dictionary)
case .solid:
return try SolidLayerModel(dictionary: dictionary)
case .image:
return try ImageLayerModel(dictionary: dictionary)
case .null:
return try LayerModel(dictionary: dictionary)
case .shape:
return try ShapeLayerModel(dictionary: dictionary)
case .text:
return try TextLayerModel(dictionary: dictionary)
case .unknown:
return try LayerModel(dictionary: dictionary)
case .none:
return nil
}
}
}
}
// MARK: - LayerModel + Sendable
/// Since `LayerModel` isn't `final`, we have to use `@unchecked Sendable` instead of `Sendable.`
/// All `LayerModel` subclasses are immutable `Sendable` values.
// swiftlint:disable:next no_unchecked_sendable
extension LayerModel: @unchecked Sendable { }
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Layers/LayerModel.swift
|
Swift
|
unknown
| 8,083
|
//
// PreCompLayer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
/// A layer that holds another animation composition.
final class PreCompLayerModel: LayerModel {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: PreCompLayerModel.CodingKeys.self)
referenceID = try container.decode(String.self, forKey: .referenceID)
timeRemapping = try container.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .timeRemapping)
width = try container.decode(Double.self, forKey: .width)
height = try container.decode(Double.self, forKey: .height)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
referenceID = try dictionary.value(for: CodingKeys.referenceID)
if let timeRemappingDictionary = dictionary[CodingKeys.timeRemapping.rawValue] as? [String: Any] {
timeRemapping = try KeyframeGroup<LottieVector1D>(dictionary: timeRemappingDictionary)
} else {
timeRemapping = nil
}
width = try dictionary.value(for: CodingKeys.width)
height = try dictionary.value(for: CodingKeys.height)
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The reference ID of the precomp.
let referenceID: String
/// A value that remaps time over time.
let timeRemapping: KeyframeGroup<LottieVector1D>?
/// Precomp Width
let width: Double
/// Precomp Height
let height: Double
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(referenceID, forKey: .referenceID)
try container.encode(timeRemapping, forKey: .timeRemapping)
try container.encode(width, forKey: .width)
try container.encode(height, forKey: .height)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case referenceID = "refId"
case timeRemapping = "tm"
case width = "w"
case height = "h"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Layers/PreCompLayerModel.swift
|
Swift
|
unknown
| 2,040
|
//
// ShapeLayer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
/// A layer that holds vector shape objects.
final class ShapeLayerModel: LayerModel {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: ShapeLayerModel.CodingKeys.self)
items = try container.decode([ShapeItem].self, ofFamily: ShapeType.self, forKey: .items)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
let itemDictionaries: [[String: Any]] = try dictionary.value(for: CodingKeys.items)
items = try [ShapeItem].fromDictionaries(itemDictionaries)
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// A list of shape items.
let items: [ShapeItem]
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(items, forKey: .items)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case items = "shapes"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Layers/ShapeLayerModel.swift
|
Swift
|
unknown
| 1,094
|
//
// SolidLayer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
/// A layer that holds a solid color.
final class SolidLayerModel: LayerModel {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: SolidLayerModel.CodingKeys.self)
colorHex = try container.decode(String.self, forKey: .colorHex)
width = try container.decode(Double.self, forKey: .width)
height = try container.decode(Double.self, forKey: .height)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
colorHex = try dictionary.value(for: CodingKeys.colorHex)
width = try dictionary.value(for: CodingKeys.width)
height = try dictionary.value(for: CodingKeys.height)
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The color of the solid in Hex // Change to value provider.
let colorHex: String
/// The Width of the color layer
let width: Double
/// The height of the color layer
let height: Double
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(colorHex, forKey: .colorHex)
try container.encode(width, forKey: .width)
try container.encode(height, forKey: .height)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case colorHex = "sc"
case width = "sw"
case height = "sh"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Layers/SolidLayerModel.swift
|
Swift
|
unknown
| 1,509
|
//
// TextLayer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
/// A layer that holds text.
final class TextLayerModel: LayerModel {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: TextLayerModel.CodingKeys.self)
let textContainer = try container.nestedContainer(keyedBy: TextCodingKeys.self, forKey: .textGroup)
text = try textContainer.decode(KeyframeGroup<TextDocument>.self, forKey: .text)
animators = try textContainer.decode([TextAnimator].self, forKey: .animators)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
let containerDictionary: [String: Any] = try dictionary.value(for: CodingKeys.textGroup)
let textDictionary: [String: Any] = try containerDictionary.value(for: TextCodingKeys.text)
text = try KeyframeGroup<TextDocument>(dictionary: textDictionary)
let animatorDictionaries: [[String: Any]] = try containerDictionary.value(for: TextCodingKeys.animators)
animators = try animatorDictionaries.map { try TextAnimator(dictionary: $0) }
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The text for the layer
let text: KeyframeGroup<TextDocument>
/// Text animators
let animators: [TextAnimator]
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
var textContainer = container.nestedContainer(keyedBy: TextCodingKeys.self, forKey: .textGroup)
try textContainer.encode(text, forKey: .text)
try textContainer.encode(animators, forKey: .animators)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case textGroup = "t"
}
private enum TextCodingKeys: String, CodingKey {
case text = "d"
case animators = "a"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Layers/TextLayerModel.swift
|
Swift
|
unknown
| 1,884
|
//
// DashPattern.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/22/19.
//
// MARK: - DashElementType
enum DashElementType: String, Codable {
case offset = "o"
case dash = "d"
case gap = "g"
}
// MARK: - DashElement
final class DashElement: Codable, DictionaryInitializable {
// MARK: Lifecycle
init(dictionary: [String: Any]) throws {
let typeRawValue: String = try dictionary.value(for: CodingKeys.type)
guard let type = DashElementType(rawValue: typeRawValue) else {
throw InitializableError.invalidInput()
}
self.type = type
let valueDictionary: [String: Any] = try dictionary.value(for: CodingKeys.value)
value = try KeyframeGroup<LottieVector1D>(dictionary: valueDictionary)
}
// MARK: Internal
enum CodingKeys: String, CodingKey {
case type = "n"
case value = "v"
}
let type: DashElementType
let value: KeyframeGroup<LottieVector1D>
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Objects/DashPattern.swift
|
Swift
|
unknown
| 928
|
//
// Marker.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/9/19.
//
/// A time marker
final class Marker: Codable, Sendable, DictionaryInitializable {
// MARK: Lifecycle
init(dictionary: [String: Any]) throws {
name = try dictionary.value(for: CodingKeys.name)
frameTime = try dictionary.value(for: CodingKeys.frameTime)
durationFrameTime = try dictionary.value(for: CodingKeys.durationFrameTime)
}
// MARK: Internal
enum CodingKeys: String, CodingKey {
case name = "cm"
case frameTime = "tm"
case durationFrameTime = "dr"
}
/// The Marker Name
let name: String
/// The Frame time of the marker
let frameTime: AnimationFrameTime
/// The duration of the marker, in frames.
let durationFrameTime: AnimationFrameTime
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Objects/Marker.swift
|
Swift
|
unknown
| 789
|
//
// Mask.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
// MARK: - MaskMode
enum MaskMode: String, Codable {
case add = "a"
case subtract = "s"
case intersect = "i"
case lighten = "l"
case darken = "d"
case difference = "f"
case none = "n"
}
// MARK: - Mask
final class Mask: Codable, DictionaryInitializable {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Mask.CodingKeys.self)
mode = try container.decodeIfPresent(MaskMode.self, forKey: .mode) ?? .add
opacity = try container
.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .opacity) ?? KeyframeGroup(LottieVector1D(100))
shape = try container.decode(KeyframeGroup<BezierPath>.self, forKey: .shape)
inverted = try container.decodeIfPresent(Bool.self, forKey: .inverted) ?? false
expansion = try container
.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .expansion) ?? KeyframeGroup(LottieVector1D(0))
}
init(dictionary: [String: Any]) throws {
if
let modeRawType = dictionary[CodingKeys.mode.rawValue] as? String,
let mode = MaskMode(rawValue: modeRawType)
{
self.mode = mode
} else {
mode = .add
}
if let opacityDictionary = dictionary[CodingKeys.opacity.rawValue] as? [String: Any] {
opacity = try KeyframeGroup<LottieVector1D>(dictionary: opacityDictionary)
} else {
opacity = KeyframeGroup(LottieVector1D(100))
}
let shapeDictionary: [String: Any] = try dictionary.value(for: CodingKeys.shape)
shape = try KeyframeGroup<BezierPath>(dictionary: shapeDictionary)
inverted = (try? dictionary.value(for: CodingKeys.inverted)) ?? false
if let expansionDictionary = dictionary[CodingKeys.expansion.rawValue] as? [String: Any] {
expansion = try KeyframeGroup<LottieVector1D>(dictionary: expansionDictionary)
} else {
expansion = KeyframeGroup(LottieVector1D(0))
}
}
// MARK: Internal
enum CodingKeys: String, CodingKey {
case mode
case opacity = "o"
case inverted = "inv"
case shape = "pt"
case expansion = "x"
}
let mode: MaskMode
let opacity: KeyframeGroup<LottieVector1D>
let shape: KeyframeGroup<BezierPath>
let inverted: Bool
let expansion: KeyframeGroup<LottieVector1D>
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Objects/Mask.swift
|
Swift
|
unknown
| 2,356
|
//
// Transform.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/7/19.
//
/// The animatable transform for a layer. Controls position, rotation, scale, and opacity.
final class Transform: Codable, DictionaryInitializable {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
/// This manual override of decode is required because we want to throw an error
/// in the case that there is not position data.
let container = try decoder.container(keyedBy: Transform.CodingKeys.self)
// AnchorPoint
anchorPoint = try container
.decodeIfPresent(KeyframeGroup<LottieVector3D>.self, forKey: .anchorPoint) ??
KeyframeGroup(LottieVector3D(x: Double(0), y: 0, z: 0))
// Position
if container.contains(.positionX), container.contains(.positionY) {
// Position dimensions are split into two keyframe groups
positionX = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .positionX)
positionY = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .positionY)
position = nil
} else if let positionKeyframes = try? container.decode(KeyframeGroup<LottieVector3D>.self, forKey: .position) {
// Position dimensions are a single keyframe group.
position = positionKeyframes
positionX = nil
positionY = nil
} else if
let positionContainer = try? container.nestedContainer(keyedBy: PositionCodingKeys.self, forKey: .position),
let positionX = try? positionContainer.decode(KeyframeGroup<LottieVector1D>.self, forKey: .positionX),
let positionY = try? positionContainer.decode(KeyframeGroup<LottieVector1D>.self, forKey: .positionY)
{
/// Position keyframes are split and nested.
self.positionX = positionX
self.positionY = positionY
position = nil
} else {
/// Default value.
position = KeyframeGroup(LottieVector3D(x: Double(0), y: 0, z: 0))
positionX = nil
positionY = nil
}
// Scale
scale = try container
.decodeIfPresent(KeyframeGroup<LottieVector3D>.self, forKey: .scale) ??
KeyframeGroup(LottieVector3D(x: Double(100), y: 100, z: 100))
// Rotation
if let rotation = try container.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .rotationX) {
rotationX = rotation
} else {
rotationX = KeyframeGroup(LottieVector1D(0))
}
if let rotation = try container.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .rotationY) {
rotationY = rotation
} else {
rotationY = KeyframeGroup(LottieVector1D(0))
}
if let rotation = try container.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .rotationZ) {
rotationZ = rotation
} else {
rotationZ = try container
.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .rotation) ?? KeyframeGroup(LottieVector1D(0))
}
rotation = nil
// Opacity
opacity = try container
.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .opacity) ?? KeyframeGroup(LottieVector1D(100))
}
init(dictionary: [String: Any]) throws {
if
let anchorPointDictionary = dictionary[CodingKeys.anchorPoint.rawValue] as? [String: Any],
let anchorPoint = try? KeyframeGroup<LottieVector3D>(dictionary: anchorPointDictionary)
{
self.anchorPoint = anchorPoint
} else {
anchorPoint = Transform.default.anchorPoint
}
if
let xDictionary = dictionary[CodingKeys.positionX.rawValue] as? [String: Any],
let yDictionary = dictionary[CodingKeys.positionY.rawValue] as? [String: Any]
{
positionX = try KeyframeGroup<LottieVector1D>(dictionary: xDictionary)
positionY = try KeyframeGroup<LottieVector1D>(dictionary: yDictionary)
position = nil
} else if
let positionDictionary = dictionary[CodingKeys.position.rawValue] as? [String: Any],
positionDictionary[KeyframeGroup<LottieVector3D>.KeyframeWrapperKey.keyframeData.rawValue] != nil
{
position = try KeyframeGroup<LottieVector3D>(dictionary: positionDictionary)
positionX = nil
positionY = nil
} else if
let positionDictionary = dictionary[CodingKeys.position.rawValue] as? [String: Any],
let xDictionary = positionDictionary[PositionCodingKeys.positionX.rawValue] as? [String: Any],
let yDictionary = positionDictionary[PositionCodingKeys.positionY.rawValue] as? [String: Any]
{
positionX = try KeyframeGroup<LottieVector1D>(dictionary: xDictionary)
positionY = try KeyframeGroup<LottieVector1D>(dictionary: yDictionary)
position = nil
} else {
position = Transform.default.position
positionX = nil
positionY = nil
}
if
let scaleDictionary = dictionary[CodingKeys.scale.rawValue] as? [String: Any],
let scale = try? KeyframeGroup<LottieVector3D>(dictionary: scaleDictionary)
{
self.scale = scale
} else {
scale = Transform.default.scale
}
if
let rotationDictionary = dictionary[CodingKeys.rotationX.rawValue] as? [String: Any],
let rotation = try? KeyframeGroup<LottieVector1D>(dictionary: rotationDictionary)
{
rotationX = rotation
} else {
rotationX = Transform.default.rotationX
}
if
let rotationDictionary = dictionary[CodingKeys.rotationY.rawValue] as? [String: Any],
let rotation = try? KeyframeGroup<LottieVector1D>(dictionary: rotationDictionary)
{
rotationY = rotation
} else {
rotationY = Transform.default.rotationY
}
if
let rotationDictionary = dictionary[CodingKeys.rotation.rawValue] as? [String: Any],
let rotation = try? KeyframeGroup<LottieVector1D>(dictionary: rotationDictionary)
{
rotationZ = rotation
} else if
let rotationDictionary = dictionary[CodingKeys.rotationZ.rawValue] as? [String: Any],
let rotation = try? KeyframeGroup<LottieVector1D>(dictionary: rotationDictionary)
{
rotationZ = rotation
} else {
rotationZ = Transform.default.rotationZ
}
rotation = nil
if
let opacityDictionary = dictionary[CodingKeys.opacity.rawValue] as? [String: Any],
let opacity = try? KeyframeGroup<LottieVector1D>(dictionary: opacityDictionary)
{
self.opacity = opacity
} else {
opacity = Transform.default.opacity
}
}
init(
anchorPoint: KeyframeGroup<LottieVector3D>,
position: KeyframeGroup<LottieVector3D>?,
positionX: KeyframeGroup<LottieVector1D>?,
positionY: KeyframeGroup<LottieVector1D>?,
scale: KeyframeGroup<LottieVector3D>,
rotationX: KeyframeGroup<LottieVector1D>,
rotationY: KeyframeGroup<LottieVector1D>,
rotationZ: KeyframeGroup<LottieVector1D>,
opacity: KeyframeGroup<LottieVector1D>,
rotation: KeyframeGroup<LottieVector1D>?)
{
self.anchorPoint = anchorPoint
self.position = position
self.positionX = positionX
self.positionY = positionY
self.scale = scale
self.rotationX = rotationX
self.rotationY = rotationY
self.rotationZ = rotationZ
self.opacity = opacity
self.rotation = rotation
}
// MARK: Internal
enum CodingKeys: String, CodingKey {
case anchorPoint = "a"
case position = "p"
case positionX = "px"
case positionY = "py"
case scale = "s"
case rotation = "r"
case rotationX = "rx"
case rotationY = "ry"
case rotationZ = "rz"
case opacity = "o"
}
enum PositionCodingKeys: String, CodingKey {
case split = "s"
case positionX = "x"
case positionY = "y"
}
/// Default transform values to use if no transform is provided
static var `default`: Transform {
Transform(
anchorPoint: KeyframeGroup(LottieVector3D(x: Double(0), y: 0, z: 0)),
position: KeyframeGroup(LottieVector3D(x: Double(0), y: 0, z: 0)),
positionX: nil,
positionY: nil,
scale: KeyframeGroup(LottieVector3D(x: Double(100), y: 100, z: 100)),
rotationX: KeyframeGroup(LottieVector1D(0)),
rotationY: KeyframeGroup(LottieVector1D(0)),
rotationZ: KeyframeGroup(LottieVector1D(0)),
opacity: KeyframeGroup(LottieVector1D(100)),
rotation: nil)
}
/// The anchor point of the transform.
let anchorPoint: KeyframeGroup<LottieVector3D>
/// The position of the transform. This is nil if the position data was split.
let position: KeyframeGroup<LottieVector3D>?
/// The positionX of the transform. This is nil if the position property is set.
let positionX: KeyframeGroup<LottieVector1D>?
/// The positionY of the transform. This is nil if the position property is set.
let positionY: KeyframeGroup<LottieVector1D>?
/// The scale of the transform.
let scale: KeyframeGroup<LottieVector3D>
/// The rotation of the transform on X axis.
let rotationX: KeyframeGroup<LottieVector1D>
/// The rotation of the transform on Y axis.
let rotationY: KeyframeGroup<LottieVector1D>
/// The rotation of the transform on Z axis.
let rotationZ: KeyframeGroup<LottieVector1D>
/// The opacity of the transform.
let opacity: KeyframeGroup<LottieVector1D>
// MARK: Private
/// Here for the CodingKeys.rotation = "r". `r` and `rz` are the same.
private let rotation: KeyframeGroup<LottieVector1D>?
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Objects/Transform.swift
|
Swift
|
unknown
| 9,298
|
//
// EllipseItem.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
// MARK: - PathDirection
enum PathDirection: Int, Codable {
case clockwise = 1
case userSetClockwise = 2
case counterClockwise = 3
}
// MARK: - Ellipse
final class Ellipse: ShapeItem {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Ellipse.CodingKeys.self)
direction = try container.decodeIfPresent(PathDirection.self, forKey: .direction) ?? .clockwise
position = try container.decode(KeyframeGroup<LottieVector3D>.self, forKey: .position)
size = try container.decode(KeyframeGroup<LottieVector3D>.self, forKey: .size)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
if
let directionRawType = dictionary[CodingKeys.direction.rawValue] as? Int,
let direction = PathDirection(rawValue: directionRawType)
{
self.direction = direction
} else {
direction = .clockwise
}
let positionDictionary: [String: Any] = try dictionary.value(for: CodingKeys.position)
position = try KeyframeGroup<LottieVector3D>(dictionary: positionDictionary)
let sizeDictionary: [String: Any] = try dictionary.value(for: CodingKeys.size)
size = try KeyframeGroup<LottieVector3D>(dictionary: sizeDictionary)
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The direction of the ellipse.
let direction: PathDirection
/// The position of the ellipse
let position: KeyframeGroup<LottieVector3D>
/// The size of the ellipse
let size: KeyframeGroup<LottieVector3D>
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(direction, forKey: .direction)
try container.encode(position, forKey: .position)
try container.encode(size, forKey: .size)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case direction = "d"
case position = "p"
case size = "s"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/ShapeItems/Ellipse.swift
|
Swift
|
unknown
| 2,108
|
//
// FillShape.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
// MARK: - FillRule
enum FillRule: Int, Codable {
case none
case nonZeroWinding
case evenOdd
}
// MARK: - Fill
final class Fill: ShapeItem {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Fill.CodingKeys.self)
opacity = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .opacity)
color = try container.decode(KeyframeGroup<LottieColor>.self, forKey: .color)
fillRule = try container.decodeIfPresent(FillRule.self, forKey: .fillRule) ?? .nonZeroWinding
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
let opacityDictionary: [String: Any] = try dictionary.value(for: CodingKeys.opacity)
opacity = try KeyframeGroup<LottieVector1D>(dictionary: opacityDictionary)
let colorDictionary: [String: Any] = try dictionary.value(for: CodingKeys.color)
color = try KeyframeGroup<LottieColor>(dictionary: colorDictionary)
if
let fillRuleRawValue = dictionary[CodingKeys.fillRule.rawValue] as? Int,
let fillRule = FillRule(rawValue: fillRuleRawValue)
{
self.fillRule = fillRule
} else {
fillRule = .nonZeroWinding
}
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The opacity of the fill
let opacity: KeyframeGroup<LottieVector1D>
/// The color keyframes for the fill
let color: KeyframeGroup<LottieColor>
/// The fill rule to use when filling a path
let fillRule: FillRule
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(opacity, forKey: .opacity)
try container.encode(color, forKey: .color)
try container.encode(fillRule, forKey: .fillRule)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case opacity = "o"
case color = "c"
case fillRule = "r"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/ShapeItems/Fill.swift
|
Swift
|
unknown
| 2,050
|
//
// GradientFill.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
// MARK: - GradientType
enum GradientType: Int, Codable, Sendable {
case none
case linear
case radial
}
// MARK: - GradientFill
final class GradientFill: ShapeItem {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: GradientFill.CodingKeys.self)
opacity = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .opacity)
startPoint = try container.decode(KeyframeGroup<LottieVector3D>.self, forKey: .startPoint)
endPoint = try container.decode(KeyframeGroup<LottieVector3D>.self, forKey: .endPoint)
gradientType = try container.decode(GradientType.self, forKey: .gradientType)
highlightLength = try container.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .highlightLength)
highlightAngle = try container.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .highlightAngle)
fillRule = try container.decodeIfPresent(FillRule.self, forKey: .fillRule) ?? .nonZeroWinding
let colorsContainer = try container.nestedContainer(keyedBy: GradientDataKeys.self, forKey: .colors)
colors = try colorsContainer.decode(KeyframeGroup<[Double]>.self, forKey: .colors)
numberOfColors = try colorsContainer.decode(Int.self, forKey: .numberOfColors)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
let opacityDictionary: [String: Any] = try dictionary.value(for: CodingKeys.opacity)
opacity = try KeyframeGroup<LottieVector1D>(dictionary: opacityDictionary)
let startPointDictionary: [String: Any] = try dictionary.value(for: CodingKeys.startPoint)
startPoint = try KeyframeGroup<LottieVector3D>(dictionary: startPointDictionary)
let endPointDictionary: [String: Any] = try dictionary.value(for: CodingKeys.endPoint)
endPoint = try KeyframeGroup<LottieVector3D>(dictionary: endPointDictionary)
let gradientRawType: Int = try dictionary.value(for: CodingKeys.gradientType)
guard let gradient = GradientType(rawValue: gradientRawType) else {
throw InitializableError.invalidInput()
}
gradientType = gradient
if let highlightLengthDictionary = dictionary[CodingKeys.highlightLength.rawValue] as? [String: Any] {
highlightLength = try? KeyframeGroup<LottieVector1D>(dictionary: highlightLengthDictionary)
} else {
highlightLength = nil
}
if let highlightAngleDictionary = dictionary[CodingKeys.highlightAngle.rawValue] as? [String: Any] {
highlightAngle = try? KeyframeGroup<LottieVector1D>(dictionary: highlightAngleDictionary)
} else {
highlightAngle = nil
}
let colorsDictionary: [String: Any] = try dictionary.value(for: CodingKeys.colors)
let nestedColorsDictionary: [String: Any] = try colorsDictionary.value(for: GradientDataKeys.colors)
colors = try KeyframeGroup<[Double]>(dictionary: nestedColorsDictionary)
numberOfColors = try colorsDictionary.value(for: GradientDataKeys.numberOfColors)
if
let fillRuleRawValue = dictionary[CodingKeys.fillRule.rawValue] as? Int,
let fillRule = FillRule(rawValue: fillRuleRawValue)
{
self.fillRule = fillRule
} else {
fillRule = .nonZeroWinding
}
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The opacity of the fill
let opacity: KeyframeGroup<LottieVector1D>
/// The start of the gradient
let startPoint: KeyframeGroup<LottieVector3D>
/// The end of the gradient
let endPoint: KeyframeGroup<LottieVector3D>
/// The type of gradient
let gradientType: GradientType
/// Gradient Highlight Length. Only if type is Radial
let highlightLength: KeyframeGroup<LottieVector1D>?
/// Highlight Angle. Only if type is Radial
let highlightAngle: KeyframeGroup<LottieVector1D>?
/// The number of color points in the gradient
let numberOfColors: Int
/// The Colors of the gradient.
let colors: KeyframeGroup<[Double]>
/// The fill rule to use when filling a path
let fillRule: FillRule
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(opacity, forKey: .opacity)
try container.encode(startPoint, forKey: .startPoint)
try container.encode(endPoint, forKey: .endPoint)
try container.encode(gradientType, forKey: .gradientType)
try container.encodeIfPresent(highlightLength, forKey: .highlightLength)
try container.encodeIfPresent(highlightAngle, forKey: .highlightAngle)
try container.encodeIfPresent(fillRule, forKey: .fillRule)
var colorsContainer = container.nestedContainer(keyedBy: GradientDataKeys.self, forKey: .colors)
try colorsContainer.encode(numberOfColors, forKey: .numberOfColors)
try colorsContainer.encode(colors, forKey: .colors)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case opacity = "o"
case startPoint = "s"
case endPoint = "e"
case gradientType = "t"
case highlightLength = "h"
case highlightAngle = "a"
case colors = "g"
case fillRule = "r"
}
private enum GradientDataKeys: String, CodingKey {
case numberOfColors = "p"
case colors = "k"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/ShapeItems/GradientFill.swift
|
Swift
|
unknown
| 5,321
|
//
// GradientStroke.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
// MARK: - LineCap
enum LineCap: Int, Codable, Sendable {
case none
case butt
case round
case square
}
// MARK: - LineJoin
enum LineJoin: Int, Codable, Sendable {
case none
case miter
case round
case bevel
}
// MARK: - GradientStroke
final class GradientStroke: ShapeItem {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: GradientStroke.CodingKeys.self)
opacity = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .opacity)
startPoint = try container.decode(KeyframeGroup<LottieVector3D>.self, forKey: .startPoint)
endPoint = try container.decode(KeyframeGroup<LottieVector3D>.self, forKey: .endPoint)
gradientType = try container.decode(GradientType.self, forKey: .gradientType)
highlightLength = try container.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .highlightLength)
highlightAngle = try container.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .highlightAngle)
width = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .width)
lineCap = try container.decodeIfPresent(LineCap.self, forKey: .lineCap) ?? .round
lineJoin = try container.decodeIfPresent(LineJoin.self, forKey: .lineJoin) ?? .round
miterLimit = try container.decodeIfPresent(Double.self, forKey: .miterLimit) ?? 4
// TODO Decode Color Objects instead of array.
let colorsContainer = try container.nestedContainer(keyedBy: GradientDataKeys.self, forKey: .colors)
colors = try colorsContainer.decode(KeyframeGroup<[Double]>.self, forKey: .colors)
numberOfColors = try colorsContainer.decode(Int.self, forKey: .numberOfColors)
dashPattern = try container.decodeIfPresent([DashElement].self, forKey: .dashPattern)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
let opacityDictionary: [String: Any] = try dictionary.value(for: CodingKeys.opacity)
opacity = try KeyframeGroup<LottieVector1D>(dictionary: opacityDictionary)
let startPointDictionary: [String: Any] = try dictionary.value(for: CodingKeys.startPoint)
startPoint = try KeyframeGroup<LottieVector3D>(dictionary: startPointDictionary)
let endPointDictionary: [String: Any] = try dictionary.value(for: CodingKeys.endPoint)
endPoint = try KeyframeGroup<LottieVector3D>(dictionary: endPointDictionary)
let gradientRawType: Int = try dictionary.value(for: CodingKeys.gradientType)
guard let gradient = GradientType(rawValue: gradientRawType) else {
throw InitializableError.invalidInput()
}
gradientType = gradient
if let highlightLengthDictionary = dictionary[CodingKeys.highlightLength.rawValue] as? [String: Any] {
highlightLength = try? KeyframeGroup<LottieVector1D>(dictionary: highlightLengthDictionary)
} else {
highlightLength = nil
}
if let highlightAngleDictionary = dictionary[CodingKeys.highlightAngle.rawValue] as? [String: Any] {
highlightAngle = try? KeyframeGroup<LottieVector1D>(dictionary: highlightAngleDictionary)
} else {
highlightAngle = nil
}
let widthDictionary: [String: Any] = try dictionary.value(for: CodingKeys.width)
width = try KeyframeGroup<LottieVector1D>(dictionary: widthDictionary)
if
let lineCapRawValue = dictionary[CodingKeys.lineCap.rawValue] as? Int,
let lineCap = LineCap(rawValue: lineCapRawValue)
{
self.lineCap = lineCap
} else {
lineCap = .round
}
if
let lineJoinRawValue = dictionary[CodingKeys.lineJoin.rawValue] as? Int,
let lineJoin = LineJoin(rawValue: lineJoinRawValue)
{
self.lineJoin = lineJoin
} else {
lineJoin = .round
}
miterLimit = (try? dictionary.value(for: CodingKeys.miterLimit)) ?? 4
let colorsDictionary: [String: Any] = try dictionary.value(for: CodingKeys.colors)
let nestedColorsDictionary: [String: Any] = try colorsDictionary.value(for: GradientDataKeys.colors)
colors = try KeyframeGroup<[Double]>(dictionary: nestedColorsDictionary)
numberOfColors = try colorsDictionary.value(for: GradientDataKeys.numberOfColors)
let dashPatternDictionaries = dictionary[CodingKeys.dashPattern.rawValue] as? [[String: Any]]
dashPattern = try? dashPatternDictionaries?.map { try DashElement(dictionary: $0) }
try super.init(dictionary: dictionary)
}
init(
name: String,
hidden: Bool,
opacity: KeyframeGroup<LottieVector1D>,
startPoint: KeyframeGroup<LottieVector3D>,
endPoint: KeyframeGroup<LottieVector3D>,
gradientType: GradientType,
highlightLength: KeyframeGroup<LottieVector1D>?,
highlightAngle: KeyframeGroup<LottieVector1D>?,
numberOfColors: Int,
colors: KeyframeGroup<[Double]>,
width: KeyframeGroup<LottieVector1D>,
lineCap: LineCap,
lineJoin: LineJoin,
miterLimit: Double,
dashPattern: [DashElement]?)
{
self.opacity = opacity
self.startPoint = startPoint
self.endPoint = endPoint
self.gradientType = gradientType
self.highlightLength = highlightLength
self.highlightAngle = highlightAngle
self.numberOfColors = numberOfColors
self.colors = colors
self.width = width
self.lineCap = lineCap
self.lineJoin = lineJoin
self.miterLimit = miterLimit
self.dashPattern = dashPattern
super.init(name: name, type: .gradientStroke, hidden: hidden)
}
// MARK: Internal
/// The opacity of the fill
let opacity: KeyframeGroup<LottieVector1D>
/// The start of the gradient
let startPoint: KeyframeGroup<LottieVector3D>
/// The end of the gradient
let endPoint: KeyframeGroup<LottieVector3D>
/// The type of gradient
let gradientType: GradientType
/// Gradient Highlight Length. Only if type is Radial
let highlightLength: KeyframeGroup<LottieVector1D>?
/// Highlight Angle. Only if type is Radial
let highlightAngle: KeyframeGroup<LottieVector1D>?
/// The number of color points in the gradient
let numberOfColors: Int
/// The Colors of the gradient.
let colors: KeyframeGroup<[Double]>
/// The width of the stroke
let width: KeyframeGroup<LottieVector1D>
/// Line Cap
let lineCap: LineCap
/// Line Join
let lineJoin: LineJoin
/// Miter Limit
let miterLimit: Double
/// The dash pattern of the stroke
let dashPattern: [DashElement]?
/// Creates a copy of this GradientStroke with the given updated width keyframes
func copy(width newWidth: KeyframeGroup<LottieVector1D>) -> GradientStroke {
GradientStroke(
name: name,
hidden: hidden,
opacity: opacity,
startPoint: startPoint,
endPoint: endPoint,
gradientType: gradientType,
highlightLength: highlightLength,
highlightAngle: highlightAngle,
numberOfColors: numberOfColors,
colors: colors,
width: newWidth,
lineCap: lineCap,
lineJoin: lineJoin,
miterLimit: miterLimit,
dashPattern: dashPattern)
}
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(opacity, forKey: .opacity)
try container.encode(startPoint, forKey: .startPoint)
try container.encode(endPoint, forKey: .endPoint)
try container.encode(gradientType, forKey: .gradientType)
try container.encodeIfPresent(highlightLength, forKey: .highlightLength)
try container.encodeIfPresent(highlightAngle, forKey: .highlightAngle)
try container.encode(width, forKey: .width)
try container.encode(lineCap, forKey: .lineCap)
try container.encode(lineJoin, forKey: .lineJoin)
try container.encode(miterLimit, forKey: .miterLimit)
var colorsContainer = container.nestedContainer(keyedBy: GradientDataKeys.self, forKey: .colors)
try colorsContainer.encode(numberOfColors, forKey: .numberOfColors)
try colorsContainer.encode(colors, forKey: .colors)
try container.encodeIfPresent(dashPattern, forKey: .dashPattern)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case opacity = "o"
case startPoint = "s"
case endPoint = "e"
case gradientType = "t"
case highlightLength = "h"
case highlightAngle = "a"
case colors = "g"
case width = "w"
case lineCap = "lc"
case lineJoin = "lj"
case miterLimit = "ml"
case dashPattern = "d"
}
private enum GradientDataKeys: String, CodingKey {
case numberOfColors = "p"
case colors = "k"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/ShapeItems/GradientStroke.swift
|
Swift
|
unknown
| 8,613
|
//
// GroupItem.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
/// An item that define a a group of shape items
final class Group: ShapeItem {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Group.CodingKeys.self)
items = try container.decode([ShapeItem].self, ofFamily: ShapeType.self, forKey: .items)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
let itemDictionaries: [[String: Any]] = try dictionary.value(for: CodingKeys.items)
items = try [ShapeItem].fromDictionaries(itemDictionaries)
try super.init(dictionary: dictionary)
}
init(items: [ShapeItem], name: String) {
self.items = items
super.init(name: name, type: .group, hidden: false)
}
// MARK: Internal
/// A list of shape items.
let items: [ShapeItem]
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(items, forKey: .items)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case items = "it"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/ShapeItems/Group.swift
|
Swift
|
unknown
| 1,199
|
//
// Merge.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
// MARK: - MergeMode
enum MergeMode: Int, Codable, Sendable {
case none
case merge
case add
case subtract
case intersect
case exclude
}
// MARK: - Merge
final class Merge: ShapeItem {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Merge.CodingKeys.self)
mode = try container.decode(MergeMode.self, forKey: .mode)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
let modeRawType: Int = try dictionary.value(for: CodingKeys.mode)
guard let mode = MergeMode(rawValue: modeRawType) else {
throw InitializableError.invalidInput()
}
self.mode = mode
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The mode of the merge path
let mode: MergeMode
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(mode, forKey: .mode)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case mode = "mm"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/ShapeItems/Merge.swift
|
Swift
|
unknown
| 1,208
|
//
// Rectangle.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
final class Rectangle: ShapeItem {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Rectangle.CodingKeys.self)
direction = try container.decodeIfPresent(PathDirection.self, forKey: .direction) ?? .clockwise
position = try container.decode(KeyframeGroup<LottieVector3D>.self, forKey: .position)
size = try container.decode(KeyframeGroup<LottieVector3D>.self, forKey: .size)
cornerRadius = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .cornerRadius)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
if
let directionRawType = dictionary[CodingKeys.direction.rawValue] as? Int,
let direction = PathDirection(rawValue: directionRawType)
{
self.direction = direction
} else {
direction = .clockwise
}
let positionDictionary: [String: Any] = try dictionary.value(for: CodingKeys.position)
position = try KeyframeGroup<LottieVector3D>(dictionary: positionDictionary)
let sizeDictionary: [String: Any] = try dictionary.value(for: CodingKeys.size)
size = try KeyframeGroup<LottieVector3D>(dictionary: sizeDictionary)
let cornerRadiusDictionary: [String: Any] = try dictionary.value(for: CodingKeys.cornerRadius)
cornerRadius = try KeyframeGroup<LottieVector1D>(dictionary: cornerRadiusDictionary)
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The direction of the rect.
let direction: PathDirection
/// The position
let position: KeyframeGroup<LottieVector3D>
/// The size
let size: KeyframeGroup<LottieVector3D>
/// The Corner radius of the rectangle
let cornerRadius: KeyframeGroup<LottieVector1D>
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(direction, forKey: .direction)
try container.encode(position, forKey: .position)
try container.encode(size, forKey: .size)
try container.encode(cornerRadius, forKey: .cornerRadius)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case direction = "d"
case position = "p"
case size = "s"
case cornerRadius = "r"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/ShapeItems/Rectangle.swift
|
Swift
|
unknown
| 2,385
|
//
// Repeater.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
final class Repeater: ShapeItem {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Repeater.CodingKeys.self)
copies = try container
.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .copies) ?? KeyframeGroup(LottieVector1D(0))
offset = try container
.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .offset) ?? KeyframeGroup(LottieVector1D(0))
let transformContainer = try container.nestedContainer(keyedBy: TransformKeys.self, forKey: .transform)
startOpacity = try transformContainer
.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .startOpacity) ?? KeyframeGroup(LottieVector1D(100))
endOpacity = try transformContainer
.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .endOpacity) ?? KeyframeGroup(LottieVector1D(100))
if let rotation = try transformContainer.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .rotation) {
rotationZ = rotation
} else if let rotation = try transformContainer.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .rotationZ) {
rotationZ = rotation
} else {
rotationZ = KeyframeGroup(LottieVector1D(0))
}
rotationX = try transformContainer
.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .rotationX) ?? KeyframeGroup(LottieVector1D(0))
rotationY = try transformContainer
.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .rotationY) ?? KeyframeGroup(LottieVector1D(0))
position = try transformContainer
.decodeIfPresent(KeyframeGroup<LottieVector3D>.self, forKey: .position) ??
KeyframeGroup(LottieVector3D(x: Double(0), y: 0, z: 0))
anchorPoint = try transformContainer
.decodeIfPresent(KeyframeGroup<LottieVector3D>.self, forKey: .anchorPoint) ??
KeyframeGroup(LottieVector3D(x: Double(0), y: 0, z: 0))
scale = try transformContainer
.decodeIfPresent(KeyframeGroup<LottieVector3D>.self, forKey: .scale) ??
KeyframeGroup(LottieVector3D(x: Double(100), y: 100, z: 100))
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
if let copiesDictionary = dictionary[CodingKeys.copies.rawValue] as? [String: Any] {
copies = try KeyframeGroup<LottieVector1D>(dictionary: copiesDictionary)
} else {
copies = KeyframeGroup(LottieVector1D(0))
}
if let offsetDictionary = dictionary[CodingKeys.offset.rawValue] as? [String: Any] {
offset = try KeyframeGroup<LottieVector1D>(dictionary: offsetDictionary)
} else {
offset = KeyframeGroup(LottieVector1D(0))
}
let transformDictionary: [String: Any] = try dictionary.value(for: CodingKeys.transform)
if let startOpacityDictionary = transformDictionary[TransformKeys.startOpacity.rawValue] as? [String: Any] {
startOpacity = try KeyframeGroup<LottieVector1D>(dictionary: startOpacityDictionary)
} else {
startOpacity = KeyframeGroup(LottieVector1D(100))
}
if let endOpacityDictionary = transformDictionary[TransformKeys.endOpacity.rawValue] as? [String: Any] {
endOpacity = try KeyframeGroup<LottieVector1D>(dictionary: endOpacityDictionary)
} else {
endOpacity = KeyframeGroup(LottieVector1D(100))
}
if let rotationDictionary = transformDictionary[TransformKeys.rotationX.rawValue] as? [String: Any] {
rotationX = try KeyframeGroup<LottieVector1D>(dictionary: rotationDictionary)
} else {
rotationX = KeyframeGroup(LottieVector1D(0))
}
if let rotationDictionary = transformDictionary[TransformKeys.rotationY.rawValue] as? [String: Any] {
rotationY = try KeyframeGroup<LottieVector1D>(dictionary: rotationDictionary)
} else {
rotationY = KeyframeGroup(LottieVector1D(0))
}
if let rotationDictionary = transformDictionary[TransformKeys.rotation.rawValue] as? [String: Any] {
rotationZ = try KeyframeGroup<LottieVector1D>(dictionary: rotationDictionary)
} else if let rotationDictionary = transformDictionary[TransformKeys.rotationZ.rawValue] as? [String: Any] {
rotationZ = try KeyframeGroup<LottieVector1D>(dictionary: rotationDictionary)
} else {
rotationZ = KeyframeGroup(LottieVector1D(0))
}
if let positionDictionary = transformDictionary[TransformKeys.position.rawValue] as? [String: Any] {
position = try KeyframeGroup<LottieVector3D>(dictionary: positionDictionary)
} else {
position = KeyframeGroup(LottieVector3D(x: Double(0), y: 0, z: 0))
}
if let anchorPointDictionary = transformDictionary[TransformKeys.anchorPoint.rawValue] as? [String: Any] {
anchorPoint = try KeyframeGroup<LottieVector3D>(dictionary: anchorPointDictionary)
} else {
anchorPoint = KeyframeGroup(LottieVector3D(x: Double(0), y: 0, z: 0))
}
if let scaleDictionary = transformDictionary[TransformKeys.scale.rawValue] as? [String: Any] {
scale = try KeyframeGroup<LottieVector3D>(dictionary: scaleDictionary)
} else {
scale = KeyframeGroup(LottieVector3D(x: Double(100), y: 100, z: 100))
}
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The number of copies to repeat
let copies: KeyframeGroup<LottieVector1D>
/// The offset of each copy
let offset: KeyframeGroup<LottieVector1D>
/// Start Opacity
let startOpacity: KeyframeGroup<LottieVector1D>
/// End opacity
let endOpacity: KeyframeGroup<LottieVector1D>
/// The rotation on X axis
let rotationX: KeyframeGroup<LottieVector1D>
/// The rotation on Y axis
let rotationY: KeyframeGroup<LottieVector1D>
/// The rotation on Z axis
let rotationZ: KeyframeGroup<LottieVector1D>
/// Anchor Point
let anchorPoint: KeyframeGroup<LottieVector3D>
/// Position
let position: KeyframeGroup<LottieVector3D>
/// Scale
let scale: KeyframeGroup<LottieVector3D>
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(copies, forKey: .copies)
try container.encode(offset, forKey: .offset)
var transformContainer = container.nestedContainer(keyedBy: TransformKeys.self, forKey: .transform)
try transformContainer.encode(startOpacity, forKey: .startOpacity)
try transformContainer.encode(endOpacity, forKey: .endOpacity)
try transformContainer.encode(rotationX, forKey: .rotationX)
try transformContainer.encode(rotationY, forKey: .rotationY)
try transformContainer.encode(rotationZ, forKey: .rotationZ)
try transformContainer.encode(position, forKey: .position)
try transformContainer.encode(anchorPoint, forKey: .anchorPoint)
try transformContainer.encode(scale, forKey: .scale)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case copies = "c"
case offset = "o"
case transform = "tr"
}
private enum TransformKeys: String, CodingKey {
case rotation = "r"
case rotationX = "rx"
case rotationY = "ry"
case rotationZ = "rz"
case startOpacity = "so"
case endOpacity = "eo"
case anchorPoint = "a"
case position = "p"
case scale = "s"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/ShapeItems/Repeater.swift
|
Swift
|
unknown
| 7,319
|
//
// RoundedCorners.swift
// Lottie
//
// Created by Duolingo on 10/31/22.
//
// MARK: - RoundedCorners
final class RoundedCorners: ShapeItem {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: RoundedCorners.CodingKeys.self)
radius = try
container.decode(
KeyframeGroup<LottieVector1D>.self,
forKey: .radius)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
let radiusDictionary: [String: Any] = try dictionary.value(for: CodingKeys.radius)
radius = try KeyframeGroup<LottieVector1D>(dictionary: radiusDictionary)
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The radius of rounded corners
let radius: KeyframeGroup<LottieVector1D>
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(radius, forKey: .radius)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case radius = "r"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/ShapeItems/RoundedCorners.swift
|
Swift
|
unknown
| 1,120
|
//
// VectorShape.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
/// An item that defines an custom shape
final class Shape: ShapeItem {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Shape.CodingKeys.self)
path = try container.decode(KeyframeGroup<BezierPath>.self, forKey: .path)
direction = try container.decodeIfPresent(PathDirection.self, forKey: .direction)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
let pathDictionary: [String: Any] = try dictionary.value(for: CodingKeys.path)
path = try KeyframeGroup<BezierPath>(dictionary: pathDictionary)
if
let directionRawValue = dictionary[CodingKeys.direction.rawValue] as? Int,
let direction = PathDirection(rawValue: directionRawValue)
{
self.direction = direction
} else {
direction = nil
}
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The Path
let path: KeyframeGroup<BezierPath>
let direction: PathDirection?
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(path, forKey: .path)
try container.encodeIfPresent(direction, forKey: .direction)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case path = "ks"
case direction = "d"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/ShapeItems/Shape.swift
|
Swift
|
unknown
| 1,491
|
//
// ShapeItem.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
// MARK: - ShapeType
enum ShapeType: String, Codable, Sendable {
case ellipse = "el"
case fill = "fl"
case gradientFill = "gf"
case group = "gr"
case gradientStroke = "gs"
case merge = "mm"
case rectangle = "rc"
case repeater = "rp"
case round = "rd"
case shape = "sh"
case star = "sr"
case stroke = "st"
case trim = "tm"
case transform = "tr"
case unknown
public init(from decoder: Decoder) throws {
self = try ShapeType(rawValue: decoder.singleValueContainer().decode(RawValue.self)) ?? .unknown
}
}
// MARK: ClassFamily
extension ShapeType: ClassFamily {
static var discriminator: Discriminator = .type
func getType() -> AnyObject.Type {
switch self {
case .ellipse:
return Ellipse.self
case .fill:
return Fill.self
case .gradientFill:
return GradientFill.self
case .group:
return Group.self
case .gradientStroke:
return GradientStroke.self
case .merge:
return Merge.self
case .rectangle:
return Rectangle.self
case .repeater:
return Repeater.self
case .round:
return RoundedCorners.self
case .shape:
return Shape.self
case .star:
return Star.self
case .stroke:
return Stroke.self
case .trim:
return Trim.self
case .transform:
return ShapeTransform.self
default:
return ShapeItem.self
}
}
}
// MARK: - ShapeItem
/// An item belonging to a Shape Layer
class ShapeItem: Codable, DictionaryInitializable {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: ShapeItem.CodingKeys.self)
name = try container.decodeIfPresent(String.self, forKey: .name) ?? "Layer"
type = try container.decode(ShapeType.self, forKey: .type)
hidden = try container.decodeIfPresent(Bool.self, forKey: .hidden) ?? false
}
required init(dictionary: [String: Any]) throws {
name = (try? dictionary.value(for: CodingKeys.name)) ?? "Layer"
type = ShapeType(rawValue: try dictionary.value(for: CodingKeys.type)) ?? .unknown
hidden = (try? dictionary.value(for: CodingKeys.hidden)) ?? false
}
init(
name: String,
type: ShapeType,
hidden: Bool)
{
self.name = name
self.type = type
self.hidden = hidden
}
// MARK: Internal
/// The name of the shape
let name: String
/// The type of shape
let type: ShapeType
let hidden: Bool
// MARK: Fileprivate
fileprivate enum CodingKeys: String, CodingKey {
case name = "nm"
case type = "ty"
case hidden = "hd"
}
}
extension [ShapeItem] {
static func fromDictionaries(_ dictionaries: [[String: Any]]) throws -> [ShapeItem] {
try dictionaries.compactMap { dictionary in
let shapeType = dictionary[ShapeItem.CodingKeys.type.rawValue] as? String
switch ShapeType(rawValue: shapeType ?? ShapeType.unknown.rawValue) {
case .ellipse:
return try Ellipse(dictionary: dictionary)
case .fill:
return try Fill(dictionary: dictionary)
case .gradientFill:
return try GradientFill(dictionary: dictionary)
case .group:
return try Group(dictionary: dictionary)
case .gradientStroke:
return try GradientStroke(dictionary: dictionary)
case .merge:
return try Merge(dictionary: dictionary)
case .rectangle:
return try Rectangle(dictionary: dictionary)
case .repeater:
return try Repeater(dictionary: dictionary)
case .round:
return try RoundedCorners(dictionary: dictionary)
case .shape:
return try Shape(dictionary: dictionary)
case .star:
return try Star(dictionary: dictionary)
case .stroke:
return try Stroke(dictionary: dictionary)
case .trim:
return try Trim(dictionary: dictionary)
case .transform:
return try ShapeTransform(dictionary: dictionary)
case .none:
return nil
default:
return try ShapeItem(dictionary: dictionary)
}
}
}
}
// MARK: - ShapeItem + Sendable
/// Since `ShapeItem` isn't `final`, we have to use `@unchecked Sendable` instead of `Sendable.`
/// All `ShapeItem` subclasses are immutable `Sendable` values.
// swiftlint:disable:next no_unchecked_sendable
extension ShapeItem: @unchecked Sendable { }
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/ShapeItems/ShapeItem.swift
|
Swift
|
unknown
| 4,438
|
//
// TransformItem.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
final class ShapeTransform: ShapeItem {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: ShapeTransform.CodingKeys.self)
anchor = try container
.decodeIfPresent(KeyframeGroup<LottieVector3D>.self, forKey: .anchor) ??
KeyframeGroup(LottieVector3D(x: Double(0), y: 0, z: 0))
position = try container
.decodeIfPresent(KeyframeGroup<LottieVector3D>.self, forKey: .position) ??
KeyframeGroup(LottieVector3D(x: Double(0), y: 0, z: 0))
scale = try container
.decodeIfPresent(KeyframeGroup<LottieVector3D>.self, forKey: .scale) ??
KeyframeGroup(LottieVector3D(x: Double(100), y: 100, z: 100))
rotationX = try container
.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .rotationX) ?? KeyframeGroup(LottieVector1D(0))
rotationY = try container
.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .rotationY) ?? KeyframeGroup(LottieVector1D(0))
if
let rotation = try container
.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .rotation)
{
rotationZ = rotation
} else if
let rotation = try container
.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .rotationZ)
{
rotationZ = rotation
} else {
rotationZ = KeyframeGroup(LottieVector1D(0))
}
opacity = try container
.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .opacity) ?? KeyframeGroup(LottieVector1D(100))
skew = try container.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .skew) ?? KeyframeGroup(LottieVector1D(0))
skewAxis = try container
.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .skewAxis) ?? KeyframeGroup(LottieVector1D(0))
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
if
let anchorDictionary = dictionary[CodingKeys.anchor.rawValue] as? [String: Any],
let anchor = try? KeyframeGroup<LottieVector3D>(dictionary: anchorDictionary)
{
self.anchor = anchor
} else {
anchor = KeyframeGroup(LottieVector3D(x: Double(0), y: 0, z: 0))
}
if
let positionDictionary = dictionary[CodingKeys.position.rawValue] as? [String: Any],
let position = try? KeyframeGroup<LottieVector3D>(dictionary: positionDictionary)
{
self.position = position
} else {
position = KeyframeGroup(LottieVector3D(x: Double(0), y: 0, z: 0))
}
if
let scaleDictionary = dictionary[CodingKeys.scale.rawValue] as? [String: Any],
let scale = try? KeyframeGroup<LottieVector3D>(dictionary: scaleDictionary)
{
self.scale = scale
} else {
scale = KeyframeGroup(LottieVector3D(x: Double(100), y: 100, z: 100))
}
if
let rotationDictionary = dictionary[CodingKeys.rotationX.rawValue] as? [String: Any],
let rotation = try? KeyframeGroup<LottieVector1D>(dictionary: rotationDictionary)
{
rotationX = rotation
} else {
rotationX = KeyframeGroup(LottieVector1D(0))
}
if
let rotationDictionary = dictionary[CodingKeys.rotationY.rawValue] as? [String: Any],
let rotation = try? KeyframeGroup<LottieVector1D>(dictionary: rotationDictionary)
{
rotationY = rotation
} else {
rotationY = KeyframeGroup(LottieVector1D(0))
}
if
let rotationDictionary = dictionary[CodingKeys.rotation.rawValue] as? [String: Any],
let rotation = try? KeyframeGroup<LottieVector1D>(dictionary: rotationDictionary)
{
rotationZ = rotation
} else if
let rotationDictionary = dictionary[CodingKeys.rotationZ.rawValue] as? [String: Any],
let rotation = try? KeyframeGroup<LottieVector1D>(dictionary: rotationDictionary)
{
rotationZ = rotation
} else {
rotationZ = KeyframeGroup(LottieVector1D(0))
}
if
let opacityDictionary = dictionary[CodingKeys.opacity.rawValue] as? [String: Any],
let opacity = try? KeyframeGroup<LottieVector1D>(dictionary: opacityDictionary)
{
self.opacity = opacity
} else {
opacity = KeyframeGroup(LottieVector1D(100))
}
if
let skewDictionary = dictionary[CodingKeys.skew.rawValue] as? [String: Any],
let skew = try? KeyframeGroup<LottieVector1D>(dictionary: skewDictionary)
{
self.skew = skew
} else {
skew = KeyframeGroup(LottieVector1D(0))
}
if
let skewAxisDictionary = dictionary[CodingKeys.skewAxis.rawValue] as? [String: Any],
let skewAxis = try? KeyframeGroup<LottieVector1D>(dictionary: skewAxisDictionary)
{
self.skewAxis = skewAxis
} else {
skewAxis = KeyframeGroup(LottieVector1D(0))
}
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// Anchor Point
let anchor: KeyframeGroup<LottieVector3D>
/// Position
let position: KeyframeGroup<LottieVector3D>
/// Scale
let scale: KeyframeGroup<LottieVector3D>
/// Rotation on X axis
let rotationX: KeyframeGroup<LottieVector1D>
/// Rotation on Y axis
let rotationY: KeyframeGroup<LottieVector1D>
/// Rotation on Z axis
let rotationZ: KeyframeGroup<LottieVector1D>
/// opacity
let opacity: KeyframeGroup<LottieVector1D>
/// Skew
let skew: KeyframeGroup<LottieVector1D>
/// Skew Axis
let skewAxis: KeyframeGroup<LottieVector1D>
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(anchor, forKey: .anchor)
try container.encode(position, forKey: .position)
try container.encode(scale, forKey: .scale)
try container.encode(rotationX, forKey: .rotationX)
try container.encode(rotationY, forKey: .rotationY)
try container.encode(rotationZ, forKey: .rotationZ)
try container.encode(opacity, forKey: .opacity)
try container.encode(skew, forKey: .skew)
try container.encode(skewAxis, forKey: .skewAxis)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case anchor = "a"
case position = "p"
case scale = "s"
case rotation = "r"
case rotationX = "rx"
case rotationY = "ry"
case rotationZ = "rz"
case opacity = "o"
case skew = "sk"
case skewAxis = "sa"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/ShapeItems/ShapeTransform.swift
|
Swift
|
unknown
| 6,430
|
//
// Star.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
// MARK: - StarType
enum StarType: Int, Codable, Sendable {
case none
case star
case polygon
}
// MARK: - Star
final class Star: ShapeItem {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Star.CodingKeys.self)
direction = try container.decodeIfPresent(PathDirection.self, forKey: .direction) ?? .clockwise
position = try container.decode(KeyframeGroup<LottieVector3D>.self, forKey: .position)
outerRadius = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .outerRadius)
outerRoundness = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .outerRoundness)
innerRadius = try container.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .innerRadius)
innerRoundness = try container.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .innerRoundness)
rotation = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .rotation)
points = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .points)
starType = try container.decode(StarType.self, forKey: .starType)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
if
let directionRawValue = dictionary[CodingKeys.direction.rawValue] as? Int,
let direction = PathDirection(rawValue: directionRawValue)
{
self.direction = direction
} else {
direction = .clockwise
}
let positionDictionary: [String: Any] = try dictionary.value(for: CodingKeys.position)
position = try KeyframeGroup<LottieVector3D>(dictionary: positionDictionary)
let outerRadiusDictionary: [String: Any] = try dictionary.value(for: CodingKeys.outerRadius)
outerRadius = try KeyframeGroup<LottieVector1D>(dictionary: outerRadiusDictionary)
let outerRoundnessDictionary: [String: Any] = try dictionary.value(for: CodingKeys.outerRoundness)
outerRoundness = try KeyframeGroup<LottieVector1D>(dictionary: outerRoundnessDictionary)
if let innerRadiusDictionary = dictionary[CodingKeys.innerRadius.rawValue] as? [String: Any] {
innerRadius = try KeyframeGroup<LottieVector1D>(dictionary: innerRadiusDictionary)
} else {
innerRadius = nil
}
if let innerRoundnessDictionary = dictionary[CodingKeys.innerRoundness.rawValue] as? [String: Any] {
innerRoundness = try KeyframeGroup<LottieVector1D>(dictionary: innerRoundnessDictionary)
} else {
innerRoundness = nil
}
let rotationDictionary: [String: Any] = try dictionary.value(for: CodingKeys.rotation)
rotation = try KeyframeGroup<LottieVector1D>(dictionary: rotationDictionary)
let pointsDictionary: [String: Any] = try dictionary.value(for: CodingKeys.points)
points = try KeyframeGroup<LottieVector1D>(dictionary: pointsDictionary)
let starTypeRawValue: Int = try dictionary.value(for: CodingKeys.starType)
guard let starType = StarType(rawValue: starTypeRawValue) else {
throw InitializableError.invalidInput()
}
self.starType = starType
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The direction of the star.
let direction: PathDirection
/// The position of the star
let position: KeyframeGroup<LottieVector3D>
/// The outer radius of the star
let outerRadius: KeyframeGroup<LottieVector1D>
/// The outer roundness of the star
let outerRoundness: KeyframeGroup<LottieVector1D>
/// The outer radius of the star
let innerRadius: KeyframeGroup<LottieVector1D>?
/// The outer roundness of the star
let innerRoundness: KeyframeGroup<LottieVector1D>?
/// The rotation of the star
let rotation: KeyframeGroup<LottieVector1D>
/// The number of points on the star
let points: KeyframeGroup<LottieVector1D>
/// The type of star
let starType: StarType
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(direction, forKey: .direction)
try container.encode(position, forKey: .position)
try container.encode(outerRadius, forKey: .outerRadius)
try container.encode(outerRoundness, forKey: .outerRoundness)
try container.encode(innerRadius, forKey: .innerRadius)
try container.encode(innerRoundness, forKey: .innerRoundness)
try container.encode(rotation, forKey: .rotation)
try container.encode(points, forKey: .points)
try container.encode(starType, forKey: .starType)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case direction = "d"
case position = "p"
case outerRadius = "or"
case outerRoundness = "os"
case innerRadius = "ir"
case innerRoundness = "is"
case rotation = "r"
case points = "pt"
case starType = "sy"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/ShapeItems/Star.swift
|
Swift
|
unknown
| 4,925
|
//
// Stroke.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
final class Stroke: ShapeItem {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Stroke.CodingKeys.self)
opacity = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .opacity)
color = try container.decode(KeyframeGroup<LottieColor>.self, forKey: .color)
width = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .width)
lineCap = try container.decodeIfPresent(LineCap.self, forKey: .lineCap) ?? .round
lineJoin = try container.decodeIfPresent(LineJoin.self, forKey: .lineJoin) ?? .round
miterLimit = try container.decodeIfPresent(Double.self, forKey: .miterLimit) ?? 4
dashPattern = try container.decodeIfPresent([DashElement].self, forKey: .dashPattern)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
let opacityDictionary: [String: Any] = try dictionary.value(for: CodingKeys.opacity)
opacity = try KeyframeGroup<LottieVector1D>(dictionary: opacityDictionary)
let colorDictionary: [String: Any] = try dictionary.value(for: CodingKeys.color)
color = try KeyframeGroup<LottieColor>(dictionary: colorDictionary)
let widthDictionary: [String: Any] = try dictionary.value(for: CodingKeys.width)
width = try KeyframeGroup<LottieVector1D>(dictionary: widthDictionary)
if
let lineCapRawValue = dictionary[CodingKeys.lineCap.rawValue] as? Int,
let lineCap = LineCap(rawValue: lineCapRawValue)
{
self.lineCap = lineCap
} else {
lineCap = .round
}
if
let lineJoinRawValue = dictionary[CodingKeys.lineJoin.rawValue] as? Int,
let lineJoin = LineJoin(rawValue: lineJoinRawValue)
{
self.lineJoin = lineJoin
} else {
lineJoin = .round
}
miterLimit = (try? dictionary.value(for: CodingKeys.miterLimit)) ?? 4
let dashPatternDictionaries = dictionary[CodingKeys.dashPattern.rawValue] as? [[String: Any]]
dashPattern = try? dashPatternDictionaries?.map { try DashElement(dictionary: $0) }
try super.init(dictionary: dictionary)
}
init(
name: String,
hidden: Bool,
opacity: KeyframeGroup<LottieVector1D>,
color: KeyframeGroup<LottieColor>,
width: KeyframeGroup<LottieVector1D>,
lineCap: LineCap,
lineJoin: LineJoin,
miterLimit: Double,
dashPattern: [DashElement]?)
{
self.opacity = opacity
self.color = color
self.width = width
self.lineCap = lineCap
self.lineJoin = lineJoin
self.miterLimit = miterLimit
self.dashPattern = dashPattern
super.init(name: name, type: .stroke, hidden: hidden)
}
// MARK: Internal
/// The opacity of the stroke
let opacity: KeyframeGroup<LottieVector1D>
/// The Color of the stroke
let color: KeyframeGroup<LottieColor>
/// The width of the stroke
let width: KeyframeGroup<LottieVector1D>
/// Line Cap
let lineCap: LineCap
/// Line Join
let lineJoin: LineJoin
/// Miter Limit
let miterLimit: Double
/// The dash pattern of the stroke
let dashPattern: [DashElement]?
/// Creates a copy of this Stroke with the given updated width keyframes
func copy(width newWidth: KeyframeGroup<LottieVector1D>) -> Stroke {
Stroke(
name: name,
hidden: hidden,
opacity: opacity,
color: color,
width: newWidth,
lineCap: lineCap,
lineJoin: lineJoin,
miterLimit: miterLimit,
dashPattern: dashPattern)
}
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(opacity, forKey: .opacity)
try container.encode(color, forKey: .color)
try container.encode(width, forKey: .width)
try container.encode(lineCap, forKey: .lineCap)
try container.encode(lineJoin, forKey: .lineJoin)
try container.encode(miterLimit, forKey: .miterLimit)
try container.encodeIfPresent(dashPattern, forKey: .dashPattern)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case opacity = "o"
case color = "c"
case width = "w"
case lineCap = "lc"
case lineJoin = "lj"
case miterLimit = "ml"
case dashPattern = "d"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/ShapeItems/Stroke.swift
|
Swift
|
unknown
| 4,332
|
//
// Trim.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
// MARK: - TrimType
enum TrimType: Int, Codable {
case simultaneously = 1
case individually = 2
}
// MARK: - Trim
final class Trim: ShapeItem {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Trim.CodingKeys.self)
start = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .start)
end = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .end)
offset = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .offset)
trimType = try container.decode(TrimType.self, forKey: .trimType)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
let startDictionary: [String: Any] = try dictionary.value(for: CodingKeys.start)
start = try KeyframeGroup<LottieVector1D>(dictionary: startDictionary)
let endDictionary: [String: Any] = try dictionary.value(for: CodingKeys.end)
end = try KeyframeGroup<LottieVector1D>(dictionary: endDictionary)
let offsetDictionary: [String: Any] = try dictionary.value(for: CodingKeys.offset)
offset = try KeyframeGroup<LottieVector1D>(dictionary: offsetDictionary)
let trimTypeRawValue: Int = try dictionary.value(for: CodingKeys.trimType)
guard let trimType = TrimType(rawValue: trimTypeRawValue) else {
throw InitializableError.invalidInput()
}
self.trimType = trimType
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The start of the trim
let start: KeyframeGroup<LottieVector1D>
/// The end of the trim
let end: KeyframeGroup<LottieVector1D>
/// The offset of the trim
let offset: KeyframeGroup<LottieVector1D>
let trimType: TrimType
/// If this trim doesn't affect the path at all then we can consider it empty
var isEmpty: Bool {
start.keyframes.count == 1
&& start.keyframes[0].value.value == 0
&& end.keyframes.count == 1
&& end.keyframes[0].value.value == 100
}
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(start, forKey: .start)
try container.encode(end, forKey: .end)
try container.encode(offset, forKey: .offset)
try container.encode(trimType, forKey: .trimType)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case start = "s"
case end = "e"
case offset = "o"
case trimType = "m"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/ShapeItems/Trim.swift
|
Swift
|
unknown
| 2,580
|
//
// Font.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/9/19.
//
// MARK: - Font
final class Font: Codable, Sendable, DictionaryInitializable {
// MARK: Lifecycle
init(dictionary: [String: Any]) throws {
name = try dictionary.value(for: CodingKeys.name)
familyName = try dictionary.value(for: CodingKeys.familyName)
style = try dictionary.value(for: CodingKeys.style)
ascent = try dictionary.value(for: CodingKeys.ascent)
}
// MARK: Internal
let name: String
let familyName: String
let style: String
let ascent: Double
// MARK: Private
private enum CodingKeys: String, CodingKey {
case name = "fName"
case familyName = "fFamily"
case style = "fStyle"
case ascent
}
}
// MARK: - FontList
/// A list of fonts
final class FontList: Codable, Sendable, DictionaryInitializable {
// MARK: Lifecycle
init(dictionary: [String: Any]) throws {
let fontDictionaries: [[String: Any]] = try dictionary.value(for: CodingKeys.fonts)
fonts = try fontDictionaries.map { try Font(dictionary: $0) }
}
// MARK: Internal
enum CodingKeys: String, CodingKey {
case fonts = "list"
}
let fonts: [Font]
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Text/Font.swift
|
Swift
|
unknown
| 1,194
|
//
// Glyph.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/9/19.
//
/// A model that holds a vector character
final class Glyph: Codable, Sendable, DictionaryInitializable {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Glyph.CodingKeys.self)
character = try container.decode(String.self, forKey: .character)
fontSize = try container.decode(Double.self, forKey: .fontSize)
fontFamily = try container.decode(String.self, forKey: .fontFamily)
fontStyle = try container.decode(String.self, forKey: .fontStyle)
width = try container.decode(Double.self, forKey: .width)
if
container.contains(.shapeWrapper),
let shapeContainer = try? container.nestedContainer(keyedBy: ShapeKey.self, forKey: .shapeWrapper),
shapeContainer.contains(.shapes)
{
shapes = try shapeContainer.decode([ShapeItem].self, ofFamily: ShapeType.self, forKey: .shapes)
} else {
shapes = []
}
}
init(dictionary: [String: Any]) throws {
character = try dictionary.value(for: CodingKeys.character)
fontSize = try dictionary.value(for: CodingKeys.fontSize)
fontFamily = try dictionary.value(for: CodingKeys.fontFamily)
fontStyle = try dictionary.value(for: CodingKeys.fontStyle)
width = try dictionary.value(for: CodingKeys.width)
if
let shapes = dictionary[CodingKeys.shapeWrapper.rawValue] as? [String: Any],
let shapeDictionaries = shapes[ShapeKey.shapes.rawValue] as? [[String: Any]]
{
self.shapes = try [ShapeItem].fromDictionaries(shapeDictionaries)
} else {
shapes = [ShapeItem]()
}
}
// MARK: Internal
/// The character
let character: String
/// The font size of the character
let fontSize: Double
/// The font family of the character
let fontFamily: String
/// The Style of the character
let fontStyle: String
/// The Width of the character
let width: Double
/// The Shape Data of the Character
let shapes: [ShapeItem]
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(character, forKey: .character)
try container.encode(fontSize, forKey: .fontSize)
try container.encode(fontFamily, forKey: .fontFamily)
try container.encode(fontStyle, forKey: .fontStyle)
try container.encode(width, forKey: .width)
var shapeContainer = container.nestedContainer(keyedBy: ShapeKey.self, forKey: .shapeWrapper)
try shapeContainer.encode(shapes, forKey: .shapes)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case character = "ch"
case fontSize = "size"
case fontFamily = "fFamily"
case fontStyle = "style"
case width = "w"
case shapeWrapper = "data"
}
private enum ShapeKey: String, CodingKey {
case shapes
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Text/Glyph.swift
|
Swift
|
unknown
| 2,894
|
//
// TextAnimator.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/9/19.
//
final class TextAnimator: Codable, DictionaryInitializable {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: TextAnimator.CodingKeys.self)
name = try container.decodeIfPresent(String.self, forKey: .name) ?? ""
let animatorContainer = try container.nestedContainer(keyedBy: TextAnimatorKeys.self, forKey: .textAnimator)
fillColor = try animatorContainer.decodeIfPresent(KeyframeGroup<LottieColor>.self, forKey: .fillColor)
strokeColor = try animatorContainer.decodeIfPresent(KeyframeGroup<LottieColor>.self, forKey: .strokeColor)
strokeWidth = try animatorContainer.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .strokeWidth)
tracking = try animatorContainer.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .tracking)
anchor = try animatorContainer.decodeIfPresent(KeyframeGroup<LottieVector3D>.self, forKey: .anchor)
position = try animatorContainer.decodeIfPresent(KeyframeGroup<LottieVector3D>.self, forKey: .position)
scale = try animatorContainer.decodeIfPresent(KeyframeGroup<LottieVector3D>.self, forKey: .scale)
skew = try animatorContainer.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .skew)
skewAxis = try animatorContainer.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .skewAxis)
rotationX = try animatorContainer.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .rotationX)
rotationY = try animatorContainer.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .rotationY)
if let rotation = try animatorContainer.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .rotation) {
rotationZ = rotation
} else if let rotation = try animatorContainer.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .rotationZ) {
rotationZ = rotation
} else {
rotationZ = nil
}
opacity = try animatorContainer.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .opacity)
}
init(dictionary: [String: Any]) throws {
name = (try? dictionary.value(for: CodingKeys.name)) ?? ""
let animatorDictionary: [String: Any] = try dictionary.value(for: CodingKeys.textAnimator)
if let fillColorDictionary = animatorDictionary[TextAnimatorKeys.fillColor.rawValue] as? [String: Any] {
fillColor = try? KeyframeGroup<LottieColor>(dictionary: fillColorDictionary)
} else {
fillColor = nil
}
if let strokeColorDictionary = animatorDictionary[TextAnimatorKeys.strokeColor.rawValue] as? [String: Any] {
strokeColor = try? KeyframeGroup<LottieColor>(dictionary: strokeColorDictionary)
} else {
strokeColor = nil
}
if let strokeWidthDictionary = animatorDictionary[TextAnimatorKeys.strokeWidth.rawValue] as? [String: Any] {
strokeWidth = try? KeyframeGroup<LottieVector1D>(dictionary: strokeWidthDictionary)
} else {
strokeWidth = nil
}
if let trackingDictionary = animatorDictionary[TextAnimatorKeys.tracking.rawValue] as? [String: Any] {
tracking = try? KeyframeGroup<LottieVector1D>(dictionary: trackingDictionary)
} else {
tracking = nil
}
if let anchorDictionary = animatorDictionary[TextAnimatorKeys.anchor.rawValue] as? [String: Any] {
anchor = try? KeyframeGroup<LottieVector3D>(dictionary: anchorDictionary)
} else {
anchor = nil
}
if let positionDictionary = animatorDictionary[TextAnimatorKeys.position.rawValue] as? [String: Any] {
position = try? KeyframeGroup<LottieVector3D>(dictionary: positionDictionary)
} else {
position = nil
}
if let scaleDictionary = animatorDictionary[TextAnimatorKeys.scale.rawValue] as? [String: Any] {
scale = try? KeyframeGroup<LottieVector3D>(dictionary: scaleDictionary)
} else {
scale = nil
}
if let skewDictionary = animatorDictionary[TextAnimatorKeys.skew.rawValue] as? [String: Any] {
skew = try? KeyframeGroup<LottieVector1D>(dictionary: skewDictionary)
} else {
skew = nil
}
if let skewAxisDictionary = animatorDictionary[TextAnimatorKeys.skewAxis.rawValue] as? [String: Any] {
skewAxis = try? KeyframeGroup<LottieVector1D>(dictionary: skewAxisDictionary)
} else {
skewAxis = nil
}
if let rotationDictionary = animatorDictionary[TextAnimatorKeys.rotationX.rawValue] as? [String: Any] {
rotationX = try? KeyframeGroup<LottieVector1D>(dictionary: rotationDictionary)
} else {
rotationX = nil
}
if let rotationDictionary = animatorDictionary[TextAnimatorKeys.rotationY.rawValue] as? [String: Any] {
rotationY = try? KeyframeGroup<LottieVector1D>(dictionary: rotationDictionary)
} else {
rotationY = nil
}
if let rotationDictionary = animatorDictionary[TextAnimatorKeys.rotation.rawValue] as? [String: Any] {
rotationZ = try? KeyframeGroup<LottieVector1D>(dictionary: rotationDictionary)
} else if let rotationDictionary = animatorDictionary[TextAnimatorKeys.rotationZ.rawValue] as? [String: Any] {
rotationZ = try? KeyframeGroup<LottieVector1D>(dictionary: rotationDictionary)
} else {
rotationZ = nil
}
if let opacityDictionary = animatorDictionary[TextAnimatorKeys.opacity.rawValue] as? [String: Any] {
opacity = try KeyframeGroup<LottieVector1D>(dictionary: opacityDictionary)
} else {
opacity = nil
}
}
// MARK: Internal
let name: String
/// Anchor
let anchor: KeyframeGroup<LottieVector3D>?
/// Position
let position: KeyframeGroup<LottieVector3D>?
/// Scale
let scale: KeyframeGroup<LottieVector3D>?
/// Skew
let skew: KeyframeGroup<LottieVector1D>?
/// Skew Axis
let skewAxis: KeyframeGroup<LottieVector1D>?
/// Rotation on X axis
let rotationX: KeyframeGroup<LottieVector1D>?
/// Rotation on Y axis
let rotationY: KeyframeGroup<LottieVector1D>?
/// Rotation on Z axis
let rotationZ: KeyframeGroup<LottieVector1D>?
/// Opacity
let opacity: KeyframeGroup<LottieVector1D>?
/// Stroke Color
let strokeColor: KeyframeGroup<LottieColor>?
/// Fill Color
let fillColor: KeyframeGroup<LottieColor>?
/// Stroke Width
let strokeWidth: KeyframeGroup<LottieVector1D>?
/// Tracking
let tracking: KeyframeGroup<LottieVector1D>?
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
var animatorContainer = container.nestedContainer(keyedBy: TextAnimatorKeys.self, forKey: .textAnimator)
try animatorContainer.encodeIfPresent(fillColor, forKey: .fillColor)
try animatorContainer.encodeIfPresent(strokeColor, forKey: .strokeColor)
try animatorContainer.encodeIfPresent(strokeWidth, forKey: .strokeWidth)
try animatorContainer.encodeIfPresent(tracking, forKey: .tracking)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
// case textSelector = "s" TODO
case textAnimator = "a"
case name = "nm"
}
private enum TextSelectorKeys: String, CodingKey {
case start = "s"
case end = "e"
case offset = "o"
}
private enum TextAnimatorKeys: String, CodingKey {
case fillColor = "fc"
case strokeColor = "sc"
case strokeWidth = "sw"
case tracking = "t"
case anchor = "a"
case position = "p"
case scale = "s"
case skew = "sk"
case skewAxis = "sa"
case rotation = "r"
case rotationX = "rx"
case rotationY = "ry"
case rotationZ = "rz"
case opacity = "o"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Text/TextAnimator.swift
|
Swift
|
unknown
| 7,605
|
//
// TextDocument.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/9/19.
//
// MARK: - TextJustification
enum TextJustification: Int, Codable {
case left
case right
case center
}
// MARK: - TextDocument
final class TextDocument: Codable, DictionaryInitializable, AnyInitializable {
// MARK: Lifecycle
init(dictionary: [String: Any]) throws {
text = try dictionary.value(for: CodingKeys.text)
fontSize = try dictionary.value(for: CodingKeys.fontSize)
fontFamily = try dictionary.value(for: CodingKeys.fontFamily)
let justificationValue: Int = try dictionary.value(for: CodingKeys.justification)
guard let justification = TextJustification(rawValue: justificationValue) else {
throw InitializableError.invalidInput()
}
self.justification = justification
tracking = try dictionary.value(for: CodingKeys.tracking)
lineHeight = try dictionary.value(for: CodingKeys.lineHeight)
baseline = try dictionary.value(for: CodingKeys.baseline)
if let fillColorRawValue = dictionary[CodingKeys.fillColorData.rawValue] {
fillColorData = try? LottieColor(value: fillColorRawValue)
} else {
fillColorData = nil
}
if let strokeColorRawValue = dictionary[CodingKeys.strokeColorData.rawValue] {
strokeColorData = try? LottieColor(value: strokeColorRawValue)
} else {
strokeColorData = nil
}
strokeWidth = try? dictionary.value(for: CodingKeys.strokeWidth)
strokeOverFill = try? dictionary.value(for: CodingKeys.strokeOverFill)
if let textFramePositionRawValue = dictionary[CodingKeys.textFramePosition.rawValue] {
textFramePosition = try? LottieVector3D(value: textFramePositionRawValue)
} else {
textFramePosition = nil
}
if let textFrameSizeRawValue = dictionary[CodingKeys.textFrameSize.rawValue] {
textFrameSize = try? LottieVector3D(value: textFrameSizeRawValue)
} else {
textFrameSize = nil
}
}
convenience init(value: Any) throws {
guard let dictionary = value as? [String: Any] else {
throw InitializableError.invalidInput()
}
try self.init(dictionary: dictionary)
}
// MARK: Internal
/// The Text
let text: String
/// The Font size
let fontSize: Double
/// The Font Family
let fontFamily: String
/// Justification
let justification: TextJustification
/// Tracking
let tracking: Int
/// Line Height
let lineHeight: Double
/// Baseline
let baseline: Double?
/// Fill Color data
let fillColorData: LottieColor?
/// Scroke Color data
let strokeColorData: LottieColor?
/// Stroke Width
let strokeWidth: Double?
/// Stroke Over Fill
let strokeOverFill: Bool?
let textFramePosition: LottieVector3D?
let textFrameSize: LottieVector3D?
// MARK: Private
private enum CodingKeys: String, CodingKey {
case text = "t"
case fontSize = "s"
case fontFamily = "f"
case justification = "j"
case tracking = "tr"
case lineHeight = "lh"
case baseline = "ls"
case fillColorData = "fc"
case strokeColorData = "sc"
case strokeWidth = "sw"
case strokeOverFill = "of"
case textFramePosition = "ps"
case textFrameSize = "sz"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Model/Text/TextDocument.swift
|
Swift
|
unknown
| 3,220
|
// Created by Cal Stephens on 12/13/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - RootAnimationLayer
/// A root `CALayer` responsible for playing a Lottie animation
protocol RootAnimationLayer: CALayer {
var lottieAnimationLayer: LottieAnimationLayer? { get set }
var currentFrame: AnimationFrameTime { get set }
var renderScale: CGFloat { get set }
var respectAnimationFrameRate: Bool { get set }
var _animationLayers: [CALayer] { get }
var imageProvider: AnimationImageProvider { get set }
var textProvider: AnimationKeypathTextProvider { get set }
var fontProvider: AnimationFontProvider { get set }
/// The `CAAnimation` key corresponding to the primary animation.
/// - `LottieAnimationView` uses this key to check if the animation is still active
var primaryAnimationKey: AnimationKey { get }
/// Whether or not this layer is currently playing an animation
/// - If the layer returns `nil`, `LottieAnimationView` determines if an animation
/// is playing by checking if there is an active animation for `primaryAnimationKey`
var isAnimationPlaying: Bool? { get }
/// Instructs this layer to remove all `CAAnimation`s,
/// other than the `CAAnimation` managed by `LottieAnimationView` (if applicable)
func removeAnimations()
func reloadImages()
func forceDisplayUpdate()
func logHierarchyKeypaths()
func allHierarchyKeypaths() -> [String]
func setValueProvider(_ valueProvider: AnyValueProvider, keypath: AnimationKeypath)
func getValue(for keypath: AnimationKeypath, atFrame: AnimationFrameTime?) -> Any?
func getOriginalValue(for keypath: AnimationKeypath, atFrame: AnimationFrameTime?) -> Any?
func layer(for keypath: AnimationKeypath) -> CALayer?
func animatorNodes(for keypath: AnimationKeypath) -> [AnimatorNode]?
}
// MARK: - AnimationKey
enum AnimationKey {
/// The primary animation and its key should be managed by `LottieAnimationView`
case managed
/// The primary animation always uses the given key
case specific(String)
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/RootAnimationLayer.swift
|
Swift
|
unknown
| 2,061
|
//
// AnimatorNodeDebugging.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/18/19.
//
extension AnimatorNode {
func printNodeTree() {
parentNode?.printNodeTree()
LottieLogger.shared.info(String(describing: type(of: self)))
if let group = self as? GroupNode {
LottieLogger.shared.info("* |Children")
group.rootNode?.printNodeTree()
LottieLogger.shared.info("*")
} else {
LottieLogger.shared.info("|")
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Debugging/AnimatorNodeDebugging.swift
|
Swift
|
unknown
| 473
|
//
// LayerDebugging.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/24/19.
//
import QuartzCore
// MARK: - LayerDebugStyle
struct LayerDebugStyle {
let anchorColor: CGColor
let boundsColor: CGColor
let anchorWidth: CGFloat
let boundsWidth: CGFloat
}
// MARK: - LayerDebugging
protocol LayerDebugging {
var debugStyle: LayerDebugStyle { get }
}
// MARK: - CustomLayerDebugging
protocol CustomLayerDebugging {
func layerForDebugging() -> CALayer
}
// MARK: - DebugLayer
class DebugLayer: CALayer {
init(style: LayerDebugStyle) {
super.init()
zPosition = 1000
bounds = CGRect(x: 0, y: 0, width: style.anchorWidth, height: style.anchorWidth)
backgroundColor = style.anchorColor
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension CALayer {
@nonobjc
public func logLayerTree(withIndent: Int = 0) {
var string = ""
for _ in 0...withIndent {
string = string + " "
}
string = string + "|_" + String(describing: self)
LottieLogger.shared.info(string)
if let sublayers {
for sublayer in sublayers {
sublayer.logLayerTree(withIndent: withIndent + 1)
}
}
}
}
// MARK: - CompositionLayer + CustomLayerDebugging
extension CompositionLayer: CustomLayerDebugging {
func layerForDebugging() -> CALayer {
contentsLayer
}
}
extension CALayer {
@nonobjc
func setDebuggingState(visible: Bool) {
var sublayers = sublayers
if let cust = self as? CustomLayerDebugging {
sublayers = cust.layerForDebugging().sublayers
}
if let sublayers {
for i in 0..<sublayers.count {
if let debugLayer = sublayers[i] as? DebugLayer {
debugLayer.removeFromSuperlayer()
break
}
}
}
if let sublayers {
for sublayer in sublayers {
sublayer.setDebuggingState(visible: visible)
}
}
if visible {
let style: LayerDebugStyle
if let layerDebugging = self as? LayerDebugging {
style = layerDebugging.debugStyle
} else {
style = LayerDebugStyle.defaultStyle()
}
let debugLayer = DebugLayer(style: style)
var container = self
if let cust = self as? CustomLayerDebugging {
container = cust.layerForDebugging()
}
container.addSublayer(debugLayer)
debugLayer.position = .zero
borderWidth = style.boundsWidth
borderColor = style.boundsColor
} else {
borderWidth = 0
borderColor = nil
}
}
}
// MARK: - MainThreadAnimationLayer + LayerDebugging
extension MainThreadAnimationLayer: LayerDebugging {
var debugStyle: LayerDebugStyle {
LayerDebugStyle.topLayerStyle()
}
}
// MARK: - NullCompositionLayer + LayerDebugging
extension NullCompositionLayer: LayerDebugging {
var debugStyle: LayerDebugStyle {
LayerDebugStyle.nullLayerStyle()
}
}
// MARK: - ShapeCompositionLayer + LayerDebugging
extension ShapeCompositionLayer: LayerDebugging {
var debugStyle: LayerDebugStyle {
LayerDebugStyle.shapeLayerStyle()
}
}
// MARK: - ShapeRenderLayer + LayerDebugging
extension ShapeRenderLayer: LayerDebugging {
var debugStyle: LayerDebugStyle {
LayerDebugStyle.shapeRenderLayerStyle()
}
}
extension LayerDebugStyle {
static func defaultStyle() -> LayerDebugStyle {
let anchorColor = CGColor.rgb(1, 0, 0)
let boundsColor = CGColor.rgb(1, 1, 0)
return LayerDebugStyle(
anchorColor: anchorColor,
boundsColor: boundsColor,
anchorWidth: 10,
boundsWidth: 2)
}
static func topLayerStyle() -> LayerDebugStyle {
let anchorColor = CGColor.rgba(1, 0.5, 0, 0)
let boundsColor = CGColor.rgb(0, 1, 0)
return LayerDebugStyle(
anchorColor: anchorColor,
boundsColor: boundsColor,
anchorWidth: 10,
boundsWidth: 2)
}
static func nullLayerStyle() -> LayerDebugStyle {
let anchorColor = CGColor.rgba(0, 0, 1, 0)
let boundsColor = CGColor.rgb(0, 1, 0)
return LayerDebugStyle(
anchorColor: anchorColor,
boundsColor: boundsColor,
anchorWidth: 10,
boundsWidth: 2)
}
static func shapeLayerStyle() -> LayerDebugStyle {
let anchorColor = CGColor.rgba(0, 1, 0, 0)
let boundsColor = CGColor.rgb(0, 1, 0)
return LayerDebugStyle(
anchorColor: anchorColor,
boundsColor: boundsColor,
anchorWidth: 10,
boundsWidth: 2)
}
static func shapeRenderLayerStyle() -> LayerDebugStyle {
let anchorColor = CGColor.rgba(0, 1, 1, 0)
let boundsColor = CGColor.rgb(0, 1, 0)
return LayerDebugStyle(
anchorColor: anchorColor,
boundsColor: boundsColor,
anchorWidth: 10,
boundsWidth: 2)
}
}
extension [LayerModel] {
var parents: [Int] {
var array = [Int]()
for layer in self {
if let parent = layer.parent {
array.append(parent)
} else {
array.append(-1)
}
}
return array
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Debugging/LayerDebugging.swift
|
Swift
|
unknown
| 4,982
|
// Created by Cal Stephens on 1/28/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
enum TestHelpers {
/// Whether or not snapshot tests are currently running in a test target
static var snapshotTestsAreRunning = false
/// Whether or not performance tests are currently running in a test target
static var performanceTestsAreRunning = false
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Debugging/TestHelpers.swift
|
Swift
|
unknown
| 362
|
//
// KeypathSearchableExtension.swift
// lottie-swift
//
// Created by Brandon Withrow on 2/4/19.
//
import QuartzCore
extension KeypathSearchable {
func animatorNodes(for keyPath: AnimationKeypath) -> [AnimatorNode]? {
// Make sure there is a current key path.
guard let currentKey = keyPath.currentKey else { return nil }
// Now try popping the keypath for wildcard / child search
guard let nextKeypath = keyPath.popKey(keypathName) else {
// We may be on the final keypath. Check for match.
if
let node = self as? AnimatorNode,
currentKey.equalsKeypath(keypathName)
{
// This is the final keypath and matches self. Return.s
return [node]
}
/// Nope. Stop Search
return nil
}
var results: [AnimatorNode] = []
if
let node = self as? AnimatorNode,
nextKeypath.currentKey == nil
{
// Keypath matched self and was the final keypath.
results.append(node)
}
for childNode in childKeypaths {
// Check if the child has any nodes matching the next keypath.
if let foundNodes = childNode.animatorNodes(for: nextKeypath) {
results.append(contentsOf: foundNodes)
}
// In this case the current key is fuzzy, and both child and self match the next keyname. Keep digging!
if
currentKey.keyPathType == .fuzzyWildcard,
let nextKeypath = keyPath.nextKeypath,
nextKeypath.equalsKeypath(childNode.keypathName),
let foundNodes = childNode.animatorNodes(for: keyPath)
{
results.append(contentsOf: foundNodes)
}
}
guard results.count > 0 else {
return nil
}
return results
}
func nodeProperties(for keyPath: AnimationKeypath) -> [AnyNodeProperty]? {
guard let nextKeypath = keyPath.popKey(keypathName) else {
/// Nope. Stop Search
return nil
}
/// Keypath matches in some way. Continue the search.
var results: [AnyNodeProperty] = []
/// Check if we have a property keypath yet
if
let propertyKey = nextKeypath.propertyKey,
let property = keypathProperties[propertyKey]
{
/// We found a property!
results.append(property)
}
if nextKeypath.nextKeypath != nil {
/// Now check child keypaths.
for child in childKeypaths {
if let childProperties = child.nodeProperties(for: nextKeypath) {
results.append(contentsOf: childProperties)
}
}
}
guard results.count > 0 else {
return nil
}
return results
}
func layer(for keyPath: AnimationKeypath) -> CALayer? {
if keyPath.nextKeypath == nil, let layerKey = keyPath.currentKey, layerKey.equalsKeypath(keypathName) {
/// We found our layer!
return keypathLayer
}
guard let nextKeypath = keyPath.popKey(keypathName) else {
/// Nope. Stop Search
return nil
}
/// Now check child keypaths.
for child in childKeypaths {
if let layer = child.layer(for: nextKeypath) {
return layer
}
}
return nil
}
/// Searches this layer's keypaths to find the keypath for the given layer
func keypath(for layer: CALayer) -> AnimationKeypath? {
let allKeypaths = layerKeypaths()
return allKeypaths[layer]
}
/// Computes the list of animation keypaths that descend from this layer
func allKeypaths(for keyPath: AnimationKeypath? = nil) -> [String] {
var allKeypaths: [String] = []
let newKeypath: AnimationKeypath
if let previousKeypath = keyPath {
newKeypath = previousKeypath.appendingKey(keypathName)
} else {
newKeypath = AnimationKeypath(keys: [keypathName])
}
allKeypaths.append(newKeypath.fullPath)
for key in keypathProperties.keys {
allKeypaths.append(newKeypath.appendingKey(key).fullPath)
}
for child in childKeypaths {
allKeypaths.append(contentsOf: child.allKeypaths(for: newKeypath))
}
return allKeypaths
}
/// Computes the list of animation keypaths that descend from this layer
func layerKeypaths(for keyPath: AnimationKeypath? = nil) -> [CALayer: AnimationKeypath] {
var allKeypaths: [CALayer: AnimationKeypath] = [:]
let newKeypath: AnimationKeypath
if let previousKeypath = keyPath {
newKeypath = previousKeypath.appendingKey(keypathName)
} else {
newKeypath = AnimationKeypath(keys: [keypathName])
}
if let layer = self as? CALayer {
allKeypaths[layer] = newKeypath
}
for child in childKeypaths {
for (layer, keypath) in child.layerKeypaths(for: newKeypath) {
allKeypaths[layer] = keypath
}
}
return allKeypaths
}
}
extension AnimationKeypath {
var currentKey: String? {
keys.first
}
var nextKeypath: String? {
guard keys.count > 1 else {
return nil
}
return keys[1]
}
var propertyKey: String? {
if nextKeypath == nil {
/// There are no more keypaths. This is a property key.
return currentKey
}
if keys.count == 2, currentKey?.keyPathType == .fuzzyWildcard {
/// The next keypath is the last and the current is a fuzzy key.
return nextKeypath
}
return nil
}
var fullPath: String {
keys.joined(separator: ".")
}
// Pops the top keypath from the stack if the keyname matches.
func popKey(_ keyname: String) -> AnimationKeypath? {
guard
let currentKey,
currentKey.equalsKeypath(keyname),
keys.count > 1
else {
// Current key either doesnt match or we are on the last key.
return nil
}
// Pop the keypath from the stack and return the new stack.
let newKeys: [String]
if currentKey.keyPathType == .fuzzyWildcard {
/// Dont remove if current key is a fuzzy wildcard, and if the next keypath doesnt equal keypathname
if
let nextKeypath,
nextKeypath.equalsKeypath(keyname)
{
/// Remove next two keypaths. This keypath breaks the wildcard.
var oldKeys = keys
oldKeys.remove(at: 0)
oldKeys.remove(at: 0)
newKeys = oldKeys
} else {
newKeys = keys
}
} else {
var oldKeys = keys
oldKeys.remove(at: 0)
newKeys = oldKeys
}
return AnimationKeypath(keys: newKeys)
}
func appendingKey(_ key: String) -> AnimationKeypath {
var newKeys = keys
newKeys.append(key)
return AnimationKeypath(keys: newKeys)
}
}
extension String {
var keyPathType: KeyType {
switch self {
case "*":
return .wildcard
case "**":
return .fuzzyWildcard
default:
return .specific
}
}
func equalsKeypath(_ keyname: String) -> Bool {
if keyPathType == .wildcard || keyPathType == .fuzzyWildcard {
return true
}
if self == keyname {
return true
}
if let index = firstIndex(of: "*") {
// Wildcard search.
let prefix = String(prefix(upTo: index))
let suffix = String(suffix(from: self.index(after: index)))
if prefix.count > 0 {
// Match prefix.
if keyname.count < prefix.count {
return false
}
let testPrefix = String(keyname.prefix(upTo: keyname.index(keyname.startIndex, offsetBy: prefix.count)))
if testPrefix != prefix {
// Prefix doesnt match
return false
}
}
if suffix.count > 0 {
// Match suffix.
if keyname.count < suffix.count {
// Suffix doesnt match
return false
}
let index = keyname.index(keyname.endIndex, offsetBy: -suffix.count)
let testSuffix = String(keyname.suffix(from: index))
if testSuffix != suffix {
return false
}
}
return true
}
return false
}
}
// MARK: - KeyType
enum KeyType {
case specific
case wildcard
case fuzzyWildcard
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Extensions/AnimationKeypathExtension.swift
|
Swift
|
unknown
| 7,901
|
//
// File.swift
//
//
// Created by Denis Koryttsev on 10.05.2022.
//
extension BlendMode {
/// The Core Image filter name for this `BlendMode`, that can be applied to a `CALayer`'s `compositingFilter`.
/// Supported compositing filters are defined here: https://developer.apple.com/library/archive/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/uid/TP30000136-SW71
var filterName: String? {
switch self {
case .normal: return nil
case .multiply: return "multiplyBlendMode"
case .screen: return "screenBlendMode"
case .overlay: return "overlayBlendMode"
case .darken: return "darkenBlendMode"
case .lighten: return "lightenBlendMode"
case .colorDodge: return "colorDodgeBlendMode"
case .colorBurn: return "colorBurnBlendMode"
case .hardLight: return "hardLightBlendMode"
case .softLight: return "softLightBlendMode"
case .difference: return "differenceBlendMode"
case .exclusion: return "exclusionBlendMode"
case .hue: return "hueBlendMode"
case .saturation: return "saturationBlendMode"
case .color: return "colorBlendMode"
case .luminosity: return "luminosityBlendMode"
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Extensions/BlendMode+Filter.swift
|
Swift
|
unknown
| 1,207
|
// Created by Cal Stephens on 1/7/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
extension CGColor {
/// Initializes a `CGColor` using the given `RGB` values
static func rgb(_ red: CGFloat, _ green: CGFloat, _ blue: CGFloat) -> CGColor {
rgba(red, green, blue, 1.0)
}
/// Initializes a `CGColor` using the given grayscale value
static func gray(_ gray: CGFloat) -> CGColor {
CGColor(
colorSpace: CGColorSpaceCreateDeviceGray(),
components: [gray, 1.0])!
}
/// Initializes a `CGColor` using the given `RGBA` values
static func rgba(_ red: CGFloat, _ green: CGFloat, _ blue: CGFloat, _ alpha: CGFloat) -> CGColor {
CGColor(
colorSpace: LottieConfiguration.shared.colorSpace,
components: [red, green, blue, alpha])!
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Extensions/CGColor+RGB.swift
|
Swift
|
unknown
| 804
|
//
// CGFloatExtensions.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/14/19.
//
import Foundation
import QuartzCore
extension CGFloat {
// MARK: Internal
var squared: CGFloat {
self * self
}
var cubed: CGFloat {
self * self * self
}
var cubicRoot: CGFloat {
CGFloat(pow(Double(self), 1.0 / 3.0))
}
func isInRangeOrEqual(_ from: CGFloat, _ to: CGFloat) -> Bool {
from <= self && self <= to
}
func isInRange(_ from: CGFloat, _ to: CGFloat) -> Bool {
from < self && self < to
}
func cubicBezierInterpolate(_ P0: CGPoint, _ P1: CGPoint, _ P2: CGPoint, _ P3: CGPoint) -> CGFloat {
var t: CGFloat
if self == P0.x {
// Handle corner cases explicitly to prevent rounding errors
t = 0
} else if self == P3.x {
t = 1
} else {
// Calculate t
let a = -P0.x + 3 * P1.x - 3 * P2.x + P3.x;
let b = 3 * P0.x - 6 * P1.x + 3 * P2.x;
let c = -3 * P0.x + 3 * P1.x;
let d = P0.x - self;
let tTemp = CGFloat.SolveCubic(a, b, c, d);
if tTemp == -1 {
return -1;
}
t = tTemp
}
// Calculate y from t
return (1 - t).cubed * P0.y + 3 * t * (1 - t).squared * P1.y + 3 * t.squared * (1 - t) * P2.y + t.cubed * P3.y;
}
func cubicBezier(_ t: CGFloat, _ c1: CGFloat, _ c2: CGFloat, _ end: CGFloat) -> CGFloat {
let t_ = (1.0 - t)
let tt_ = t_ * t_
let ttt_ = t_ * t_ * t_
let tt = t * t
let ttt = t * t * t
return self * ttt_
+ 3.0 * c1 * tt_ * t
+ 3.0 * c2 * t_ * tt
+ end * ttt;
}
// MARK: Fileprivate
fileprivate static func SolveQuadratic(_ a: CGFloat, _ b: CGFloat, _ c: CGFloat) -> CGFloat {
var result = (-b + sqrt(b.squared - 4 * a * c)) / (2 * a);
guard !result.isInRangeOrEqual(0, 1) else {
return result
}
result = (-b - sqrt(b.squared - 4 * a * c)) / (2 * a);
guard !result.isInRangeOrEqual(0, 1) else {
return result
}
return -1;
}
fileprivate static func SolveCubic(_ a: CGFloat, _ b: CGFloat, _ c: CGFloat, _ d: CGFloat) -> CGFloat {
if a == 0 {
return SolveQuadratic(b, c, d)
}
if d == 0 {
return 0
}
let a = a
var b = b
var c = c
var d = d
b /= a
c /= a
d /= a
var q = (3.0 * c - b.squared) / 9.0
let r = (-27.0 * d + b * (9.0 * c - 2.0 * b.squared)) / 54.0
let disc = q.cubed + r.squared
let term1 = b / 3.0
if disc > 0 {
var s = r + sqrt(disc)
s = (s < 0) ? -((-s).cubicRoot) : s.cubicRoot
var t = r - sqrt(disc)
t = (t < 0) ? -((-t).cubicRoot) : t.cubicRoot
let result = -term1 + s + t;
if result.isInRangeOrEqual(0, 1) {
return result
}
} else if disc == 0 {
let r13 = (r < 0) ? -((-r).cubicRoot) : r.cubicRoot;
var result = -term1 + 2.0 * r13;
if result.isInRangeOrEqual(0, 1) {
return result
}
result = -(r13 + term1);
if result.isInRangeOrEqual(0, 1) {
return result
}
} else {
q = -q;
var dum1 = q * q * q;
dum1 = acos(r / sqrt(dum1));
let r13 = 2.0 * sqrt(q);
var result = -term1 + r13 * cos(dum1 / 3.0);
if result.isInRangeOrEqual(0, 1) {
return result
}
result = -term1 + r13 * cos((dum1 + 2.0 * .pi) / 3.0);
if result.isInRangeOrEqual(0, 1) {
return result
}
result = -term1 + r13 * cos((dum1 + 4.0 * .pi) / 3.0);
if result.isInRangeOrEqual(0, 1) {
return result
}
}
return -1;
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Extensions/CGFloatExtensions.swift
|
Swift
|
unknown
| 3,571
|
//
// DataExtension.swift
// Lottie
//
// Created by René Fouquet on 03.05.21.
//
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif
extension Data {
init(assetName: String, in bundle: Bundle) throws {
#if canImport(UIKit)
if let asset = NSDataAsset(name: assetName, bundle: bundle) {
self = asset.data
return
} else {
throw DotLottieError.assetNotFound(name: assetName, bundle: bundle)
}
#else
if #available(macOS 10.11, *) {
if let asset = NSDataAsset(name: assetName, bundle: bundle) {
self = asset.data
return
} else {
throw DotLottieError.assetNotFound(name: assetName, bundle: bundle)
}
}
throw DotLottieError.loadingFromAssetNotSupported
#endif
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Extensions/DataExtension.swift
|
Swift
|
unknown
| 793
|
//
// MathKit.swift
// UIToolBox
//
// Created by Brandon Withrow on 10/10/18.
//
// From https://github.com/buba447/UIToolBox
import CoreGraphics
import Foundation
extension Int {
var cgFloat: CGFloat {
CGFloat(self)
}
}
extension Double {
var cgFloat: CGFloat {
CGFloat(self)
}
}
// MARK: - CGFloat + Interpolatable
extension CGFloat {
func remap(fromLow: CGFloat, fromHigh: CGFloat, toLow: CGFloat, toHigh: CGFloat) -> CGFloat {
guard (fromHigh - fromLow) != 0 else {
// Would produce NAN
return 0
}
return toLow + (self - fromLow) * (toHigh - toLow) / (fromHigh - fromLow)
}
/// Returns a value that is clamped between the two numbers
///
/// 1. The order of arguments does not matter.
func clamp(_ a: CGFloat, _ b: CGFloat) -> CGFloat {
CGFloat(Double(self).clamp(Double(a), Double(b)))
}
/// Returns the difference between the receiver and the given number.
/// - Parameter absolute: If *true* (Default) the returned value will always be positive.
func diff(_ a: CGFloat, absolute: Bool = true) -> CGFloat {
absolute ? abs(a - self) : a - self
}
func toRadians() -> CGFloat { self * .pi / 180 }
func toDegrees() -> CGFloat { self * 180 / .pi }
}
// MARK: - Double
extension Double {
func remap(fromLow: Double, fromHigh: Double, toLow: Double, toHigh: Double) -> Double {
toLow + (self - fromLow) * (toHigh - toLow) / (fromHigh - fromLow)
}
/// Returns a value that is clamped between the two numbers
///
/// 1. The order of arguments does not matter.
func clamp(_ a: Double, _ b: Double) -> Double {
let minValue = a <= b ? a : b
let maxValue = a <= b ? b : a
return max(min(self, maxValue), minValue)
}
}
extension CGRect {
// MARK: Lifecycle
/// Initializes a new CGRect with a center point and size.
init(center: CGPoint, size: CGSize) {
self.init(
x: center.x - (size.width * 0.5),
y: center.y - (size.height * 0.5),
width: size.width,
height: size.height)
}
// MARK: Internal
/// Returns the total area of the rect.
var area: CGFloat {
width * height
}
/// The center point of the rect. Settable.
var center: CGPoint {
get {
CGPoint(x: midX, y: midY)
}
set {
origin = CGPoint(
x: newValue.x - (size.width * 0.5),
y: newValue.y - (size.height * 0.5))
}
}
/// The top left point of the rect. Settable.
var topLeft: CGPoint {
get {
CGPoint(x: minX, y: minY)
}
set {
origin = CGPoint(
x: newValue.x,
y: newValue.y)
}
}
/// The bottom left point of the rect. Settable.
var bottomLeft: CGPoint {
get {
CGPoint(x: minX, y: maxY)
}
set {
origin = CGPoint(
x: newValue.x,
y: newValue.y - size.height)
}
}
/// The top right point of the rect. Settable.
var topRight: CGPoint {
get {
CGPoint(x: maxX, y: minY)
}
set {
origin = CGPoint(
x: newValue.x - size.width,
y: newValue.y)
}
}
/// The bottom right point of the rect. Settable.
var bottomRight: CGPoint {
get {
CGPoint(x: maxX, y: maxY)
}
set {
origin = CGPoint(
x: newValue.x - size.width,
y: newValue.y - size.height)
}
}
}
extension CGSize {
/// Operator convenience to add sizes with +
static func +(left: CGSize, right: CGSize) -> CGSize {
left.add(right)
}
/// Operator convenience to subtract sizes with -
static func -(left: CGSize, right: CGSize) -> CGSize {
left.subtract(right)
}
/// Operator convenience to multiply sizes with *
static func *(left: CGSize, right: CGFloat) -> CGSize {
CGSize(width: left.width * right, height: left.height * right)
}
/// Returns the scale float that will fit the receive inside of the given size.
func scaleThatFits(_ size: CGSize) -> CGFloat {
CGFloat.minimum(width / size.width, height / size.height)
}
/// Adds receiver size to give size.
func add(_ size: CGSize) -> CGSize {
CGSize(width: width + size.width, height: height + size.height)
}
/// Subtracts given size from receiver size.
func subtract(_ size: CGSize) -> CGSize {
CGSize(width: width - size.width, height: height - size.height)
}
/// Multiplies receiver size by the given size.
func multiply(_ size: CGSize) -> CGSize {
CGSize(width: width * size.width, height: height * size.height)
}
}
// MARK: - CGLine
/// A struct that defines a line segment with two CGPoints
struct CGLine {
// MARK: Lifecycle
/// Initializes a line segment with start and end points
init(start: CGPoint, end: CGPoint) {
self.start = start
self.end = end
}
// MARK: Internal
/// The Start of the line segment.
var start: CGPoint
/// The End of the line segment.
var end: CGPoint
/// The length of the line segment.
var length: CGFloat {
end.distanceTo(start)
}
/// Returns a line segment that is normalized to a length of 1
func normalize() -> CGLine {
let len = length
guard len > 0 else {
return self
}
let relativeEnd = end - start
let relativeVector = CGPoint(x: relativeEnd.x / len, y: relativeEnd.y / len)
let absoluteVector = relativeVector + start
return CGLine(start: start, end: absoluteVector)
}
/// Trims a line segment to the given length
func trimmedToLength(_ toLength: CGFloat) -> CGLine {
let len = length
guard len > 0 else {
return self
}
let relativeEnd = end - start
let relativeVector = CGPoint(x: relativeEnd.x / len, y: relativeEnd.y / len)
let sizedVector = CGPoint(x: relativeVector.x * toLength, y: relativeVector.y * toLength)
let absoluteVector = sizedVector + start
return CGLine(start: start, end: absoluteVector)
}
/// Flips a line vertically and horizontally from the start point.
func flipped() -> CGLine {
let relativeEnd = end - start
let flippedEnd = CGPoint(x: relativeEnd.x * -1, y: relativeEnd.y * -1)
return CGLine(start: start, end: flippedEnd + start)
}
/// Move the line to the new start point.
func transpose(_ toPoint: CGPoint) -> CGLine {
let diff = toPoint - start
let newEnd = end + diff
return CGLine(start: toPoint, end: newEnd)
}
}
infix operator +|
infix operator +-
extension CGPoint {
/// Returns the length between the receiver and *CGPoint.zero*
var vectorLength: CGFloat {
distanceTo(.zero)
}
var isZero: Bool {
x == 0 && y == 0
}
/// Operator convenience to divide points with /
static func / (lhs: CGPoint, rhs: CGFloat) -> CGPoint {
CGPoint(x: lhs.x / CGFloat(rhs), y: lhs.y / CGFloat(rhs))
}
/// Operator convenience to multiply points with *
static func * (lhs: CGPoint, rhs: CGFloat) -> CGPoint {
CGPoint(x: lhs.x * CGFloat(rhs), y: lhs.y * CGFloat(rhs))
}
/// Operator convenience to add points with +
static func +(left: CGPoint, right: CGPoint) -> CGPoint {
left.add(right)
}
/// Operator convenience to subtract points with -
static func -(left: CGPoint, right: CGPoint) -> CGPoint {
left.subtract(right)
}
static func +|(left: CGPoint, right: CGFloat) -> CGPoint {
CGPoint(x: left.x, y: left.y + right)
}
static func +-(left: CGPoint, right: CGFloat) -> CGPoint {
CGPoint(x: left.x + right, y: left.y)
}
/// Returns the distance between the receiver and the given point.
func distanceTo(_ a: CGPoint) -> CGFloat {
let xDist = a.x - x
let yDist = a.y - y
return CGFloat(sqrt((xDist * xDist) + (yDist * yDist)))
}
func rounded(decimal: CGFloat) -> CGPoint {
CGPoint(x: round(decimal * x) / decimal, y: round(decimal * y) / decimal)
}
func interpolate(
_ to: CGPoint,
outTangent: CGPoint,
inTangent: CGPoint,
amount: CGFloat,
maxIterations: Int = 3,
samples: Int = 20,
accuracy: CGFloat = 1)
-> CGPoint
{
if amount == 0 {
return self
}
if amount == 1 {
return to
}
if
colinear(outTangent, inTangent) == true,
outTangent.colinear(inTangent, to) == true
{
return interpolate(to: to, amount: amount)
}
let step = 1 / CGFloat(samples)
var points: [(point: CGPoint, distance: CGFloat)] = [(point: self, distance: 0)]
var totalLength: CGFloat = 0
var previousPoint = self
var previousAmount = CGFloat(0)
var closestPoint = 0
while previousAmount < 1 {
previousAmount = previousAmount + step
if previousAmount < amount {
closestPoint = closestPoint + 1
}
let newPoint = pointOnPath(to, outTangent: outTangent, inTangent: inTangent, amount: previousAmount)
let distance = previousPoint.distanceTo(newPoint)
totalLength = totalLength + distance
points.append((point: newPoint, distance: totalLength))
previousPoint = newPoint
}
let accurateDistance = amount * totalLength
var point = points[closestPoint]
var foundPoint = false
var pointAmount = CGFloat(closestPoint) * step
var nextPointAmount: CGFloat = pointAmount + step
var refineIterations = 0
while foundPoint == false {
refineIterations = refineIterations + 1
/// First see if the next point is still less than the projected length.
let nextPoint = points[min(closestPoint + 1, points.indices.last!)]
if nextPoint.distance < accurateDistance {
point = nextPoint
closestPoint = closestPoint + 1
pointAmount = CGFloat(closestPoint) * step
nextPointAmount = pointAmount + step
if closestPoint == points.count {
foundPoint = true
}
continue
}
if accurateDistance < point.distance {
closestPoint = closestPoint - 1
if closestPoint < 0 {
foundPoint = true
continue
}
point = points[closestPoint]
pointAmount = CGFloat(closestPoint) * step
nextPointAmount = pointAmount + step
continue
}
/// Now we are certain the point is the closest point under the distance
let pointDiff = nextPoint.distance - point.distance
let proposedPointAmount = ((accurateDistance - point.distance) / pointDiff)
.remap(fromLow: 0, fromHigh: 1, toLow: pointAmount, toHigh: nextPointAmount)
let newPoint = pointOnPath(to, outTangent: outTangent, inTangent: inTangent, amount: proposedPointAmount)
let newDistance = point.distance + point.point.distanceTo(newPoint)
pointAmount = proposedPointAmount
point = (point: newPoint, distance: newDistance)
if
accurateDistance - newDistance <= accuracy ||
newDistance - accurateDistance <= accuracy
{
foundPoint = true
}
if refineIterations == maxIterations {
foundPoint = true
}
}
return point.point
}
func pointOnPath(_ to: CGPoint, outTangent: CGPoint, inTangent: CGPoint, amount: CGFloat) -> CGPoint {
let a = interpolate(to: outTangent, amount: amount)
let b = outTangent.interpolate(to: inTangent, amount: amount)
let c = inTangent.interpolate(to: to, amount: amount)
let d = a.interpolate(to: b, amount: amount)
let e = b.interpolate(to: c, amount: amount)
let f = d.interpolate(to: e, amount: amount)
return f
}
func colinear(_ a: CGPoint, _ b: CGPoint) -> Bool {
let area = x * (a.y - b.y) + a.x * (b.y - y) + b.x * (y - a.y);
let accuracy: CGFloat = 0.05
if area < accuracy, area > -accuracy {
return true
}
return false
}
/// Subtracts the given point from the receiving point.
func subtract(_ point: CGPoint) -> CGPoint {
CGPoint(
x: x - point.x,
y: y - point.y)
}
/// Adds the given point from the receiving point.
func add(_ point: CGPoint) -> CGPoint {
CGPoint(
x: x + point.x,
y: y + point.y)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Extensions/MathKit.swift
|
Swift
|
unknown
| 11,910
|
//
// StringExtensions.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/25/19.
//
import CoreGraphics
import Foundation
extension String {
var cgColor: CGColor {
let (red, green, blue) = hexColorComponents()
return .rgb(red, green, blue)
}
var lottieColor: LottieColor {
let (red, green, blue) = hexColorComponents()
return .init(r: red, g: green, b: blue, a: 1.0)
}
func hexColorComponents() -> (red: CGFloat, green: CGFloat, blue: CGFloat) {
var cString: String = trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if cString.hasPrefix("#") {
cString.remove(at: cString.startIndex)
}
if (cString.count) != 6 {
return (red: 0, green: 0, blue: 0)
}
var rgbValue: UInt64 = 0
Scanner(string: cString).scanHexInt64(&rgbValue)
return (
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Extensions/StringExtensions.swift
|
Swift
|
unknown
| 1,007
|
//
// AnimationContext.swift
// lottie-swift
//
// Created by Brandon Withrow on 2/1/19.
//
import Foundation
import QuartzCore
/// A completion block for animations.
/// - `true` is passed in if the animation completed playing.
/// - `false` is passed in if the animation was interrupted and did not complete playing.
public typealias LottieCompletionBlock = (_ completed: Bool) -> Void
// MARK: - AnimationContext
struct AnimationContext {
init(
playFrom: AnimationFrameTime,
playTo: AnimationFrameTime,
closure: LottieCompletionBlock?)
{
self.playTo = playTo
self.playFrom = playFrom
self.closure = AnimationCompletionDelegate(completionBlock: closure)
}
var playFrom: AnimationFrameTime
var playTo: AnimationFrameTime
var closure: AnimationCompletionDelegate
}
// MARK: Equatable
extension AnimationContext: Equatable {
/// Whether or not the two given `AnimationContext`s are functionally equivalent
/// - This checks whether or not a completion handler was provided,
/// but does not check whether or not the two completion handlers are equivalent.
static func == (_ lhs: AnimationContext, _ rhs: AnimationContext) -> Bool {
lhs.playTo == rhs.playTo
&& lhs.playFrom == rhs.playFrom
&& (lhs.closure.completionBlock == nil) == (rhs.closure.completionBlock == nil)
}
}
// MARK: - AnimationContextState
enum AnimationContextState {
case playing
case cancelled
case complete
}
// MARK: - AnimationCompletionDelegate
class AnimationCompletionDelegate: NSObject, CAAnimationDelegate {
// MARK: Lifecycle
init(completionBlock: LottieCompletionBlock?) {
self.completionBlock = completionBlock
super.init()
}
// MARK: Public
public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
guard ignoreDelegate == false else { return }
animationState = flag ? .complete : .cancelled
if let animationLayer, let key = animationKey {
animationLayer.removeAnimation(forKey: key)
if flag {
animationLayer.currentFrame = (anim as! CABasicAnimation).toValue as! CGFloat
}
}
if let completionBlock {
completionBlock(flag)
}
}
// MARK: Internal
var animationLayer: RootAnimationLayer?
var animationKey: String?
var ignoreDelegate = false
var animationState: AnimationContextState = .playing
let completionBlock: LottieCompletionBlock?
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Helpers/AnimationContext.swift
|
Swift
|
unknown
| 2,417
|
// Created by miguel_jimenez on 8/2/23.
// Copyright © 2023 Airbnb Inc. All rights reserved.
// MARK: - AnyEquatable
struct AnyEquatable {
private let value: Any
private let equals: (Any) -> Bool
init<T: Equatable>(_ value: T) {
self.value = value
equals = { $0 as? T == value }
}
}
// MARK: Equatable
extension AnyEquatable: Equatable {
static func ==(lhs: AnyEquatable, rhs: AnyEquatable) -> Bool {
lhs.equals(rhs.value)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Helpers/AnyEquatable.swift
|
Swift
|
unknown
| 457
|
// Created by miguel_jimenez on 7/27/23.
// Copyright © 2023 Airbnb Inc. All rights reserved.
#if canImport(SwiftUI)
import SwiftUI
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
extension Binding {
/// Helper to transform a `Binding` from one `Value` type to another.
func map<Transformed>(transform: @escaping (Value) -> Transformed) -> Binding<Transformed> {
.init {
transform(wrappedValue)
} set: { newValue in
guard let newValue = newValue as? Value else { return }
self.wrappedValue = newValue
}
}
}
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Helpers/Binding+Map.swift
|
Swift
|
unknown
| 554
|
// Created by miguel_jimenez on 7/26/23.
// Copyright © 2023 Airbnb Inc. All rights reserved.
#if canImport(Combine) && canImport(SwiftUI)
import Combine
import SwiftUI
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
extension View {
/// A backwards compatible wrapper for iOS 14 `onChange`
@ViewBuilder
func valueChanged<T: Equatable>(value: T, onChange: @escaping (T) -> Void) -> some View {
if #available(iOS 14.0, *, macOS 11.0, tvOS 14.0) {
self.onChange(of: value, perform: onChange)
} else {
onReceive(Just(value)) { value in
onChange(value)
}
}
}
}
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Helpers/View+ValueChanged.swift
|
Swift
|
unknown
| 613
|
//
// InterpolatableExtensions.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/14/19.
//
import CoreGraphics
import Foundation
extension LottieColor {
// MARK: Lifecycle
/// Initialize a new color with Hue Saturation and Value
init(h: Double, s: Double, v: Double, a: Double) {
let i = floor(h * 6)
let f = h * 6 - i
let p = v * (1 - s);
let q = v * (1 - f * s)
let t = v * (1 - (1 - f) * s)
switch i.truncatingRemainder(dividingBy: 6) {
case 0:
r = v
g = t
b = p
case 1:
r = q
g = v
b = p
case 2:
r = p
g = v
b = t
case 3:
r = p
g = q
b = v
case 4:
r = t
g = p
b = v
case 5:
r = v
g = p
b = q
default:
r = 0
g = 0
b = 0
}
self.a = a
}
init(y: Double, u: Double, v: Double, a: Double) {
// From https://www.fourcc.org/fccyvrgb.php
r = y + 1.403 * v
g = y - 0.344 * u
b = y + 1.770 * u
self.a = a
}
// MARK: Internal
/// Hue Saturation Value of the color.
var hsva: (h: Double, s: Double, v: Double, a: Double) {
let maxValue = max(r, g, b)
let minValue = min(r, g, b)
var h: Double, s: Double, v: Double = maxValue
let d = maxValue - minValue
s = maxValue == 0 ? 0 : d / maxValue;
if maxValue == minValue {
h = 0; // achromatic
} else {
switch maxValue {
case r: h = (g - b) / d + (g < b ? 6 : 0)
case g: h = (b - r) / d + 2
case b: h = (r - g) / d + 4
default: h = maxValue
}
h = h / 6
}
return (h: h, s: s, v: v, a: a)
}
var yuv: (y: Double, u: Double, v: Double, a: Double) {
/// From https://www.fourcc.org/fccyvrgb.php
let y = 0.299 * r + 0.587 * g + 0.114 * b
let u = -0.14713 * r - 0.28886 * g + 0.436 * b
let v = 0.615 * r - 0.51499 * g - 0.10001 * b
return (y: y, u: u, v: v, a: a)
}
}
// MARK: - CurveVertex + Interpolatable
extension CurveVertex: Interpolatable {
func interpolate(to: CurveVertex, amount: CGFloat) -> CurveVertex {
CurveVertex(
point: point.interpolate(to: to.point, amount: amount),
inTangent: inTangent.interpolate(to: to.inTangent, amount: amount),
outTangent: outTangent.interpolate(to: to.outTangent, amount: amount))
}
}
// MARK: - BezierPath + Interpolatable
extension BezierPath: Interpolatable {
func interpolate(to: BezierPath, amount: CGFloat) -> BezierPath {
var newPath = BezierPath()
for i in 0..<min(elements.count, to.elements.count) {
let fromVertex = elements[i].vertex
let toVertex = to.elements[i].vertex
newPath.addVertex(fromVertex.interpolate(to: toVertex, amount: amount))
}
return newPath
}
}
// MARK: - TextDocument + Interpolatable
extension TextDocument: Interpolatable {
func interpolate(to: TextDocument, amount: CGFloat) -> TextDocument {
if amount == 1 {
return to
}
return self
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Interpolatable/InterpolatableExtensions.swift
|
Swift
|
unknown
| 2,997
|
//
// KeyframeExtensions.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/14/19.
//
import CoreGraphics
import Foundation
extension Keyframe where T: AnyInterpolatable {
func interpolate(to: Keyframe<T>, progress: CGFloat) -> T {
value._interpolate(
to: to.value,
amount: progress,
spatialOutTangent: spatialOutTangent?.pointValue,
spatialInTangent: to.spatialInTangent?.pointValue)
}
}
extension Keyframe {
/// Interpolates the keyTime into a value from 0-1
func interpolatedProgress(_ to: Keyframe, keyTime: CGFloat) -> CGFloat {
let startTime = time
let endTime = to.time
if keyTime <= startTime {
return 0
}
if endTime <= keyTime {
return 1
}
if isHold {
return 0
}
let outTanPoint = outTangent?.pointValue ?? .zero
let inTanPoint = to.inTangent?.pointValue ?? CGPoint(x: 1, y: 1)
var progress: CGFloat = keyTime.remap(fromLow: startTime, fromHigh: endTime, toLow: 0, toHigh: 1)
if !outTanPoint.isZero || !inTanPoint.equalTo(CGPoint(x: 1, y: 1)) {
/// Cubic interpolation
progress = progress.cubicBezierInterpolate(.zero, outTanPoint, inTanPoint, CGPoint(x: 1, y: 1))
}
return progress
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Interpolatable/KeyframeExtensions.swift
|
Swift
|
unknown
| 1,237
|
//
// KeyframeInterpolator.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/15/19.
//
import CoreGraphics
import Foundation
// MARK: - KeyframeInterpolator
/// A value provider that produces a value at Time from a group of keyframes
final class KeyframeInterpolator<ValueType>: ValueProvider where ValueType: AnyInterpolatable {
// MARK: Lifecycle
init(keyframes: ContiguousArray<Keyframe<ValueType>>) {
self.keyframes = keyframes
}
// MARK: Internal
let keyframes: ContiguousArray<Keyframe<ValueType>>
var valueType: Any.Type {
ValueType.self
}
var storage: ValueProviderStorage<ValueType> {
.closure { [self] frame in
// First set the keyframe span for the frame.
updateSpanIndices(frame: frame)
lastUpdatedFrame = frame
// If only one keyframe return its value
let progress: CGFloat
let value: ValueType
if
let leading = leadingKeyframe,
let trailing = trailingKeyframe
{
/// We have leading and trailing keyframe.
progress = leading.interpolatedProgress(trailing, keyTime: frame)
value = leading.interpolate(to: trailing, progress: progress)
} else if let leading = leadingKeyframe {
progress = 0
value = leading.value
} else if let trailing = trailingKeyframe {
progress = 1
value = trailing.value
} else {
/// Satisfy the compiler.
progress = 0
value = keyframes[0].value
}
return value
}
}
/// Returns true to trigger a frame update for this interpolator.
///
/// An interpolator will be asked if it needs to update every frame.
/// If the interpolator needs updating it will be asked to compute its value for
/// the given frame.
///
/// Cases a keyframe should not be updated:
/// - If time is in span and leading keyframe is hold
/// - If time is after the last keyframe.
/// - If time is before the first keyframe
///
/// Cases for updating a keyframe:
/// - If time is in the span, and is not a hold
/// - If time is outside of the span, and there are more keyframes
/// - If a value delegate is set
/// - If leading and trailing are both nil.
func hasUpdate(frame: CGFloat) -> Bool {
if lastUpdatedFrame == nil {
return true
}
if
let leading = leadingKeyframe,
trailingKeyframe == nil,
leading.time < frame
{
/// Frame is after bounds of keyframes
return false
}
if
let trailing = trailingKeyframe,
leadingKeyframe == nil,
frame < trailing.time
{
/// Frame is before bounds of keyframes
return false
}
if
let leading = leadingKeyframe,
let trailing = trailingKeyframe,
leading.isHold,
leading.time < frame,
frame < trailing.time
{
return false
}
return true
}
// MARK: Fileprivate
fileprivate var lastUpdatedFrame: CGFloat?
fileprivate var leadingIndex: Int? = nil
fileprivate var trailingIndex: Int? = nil
fileprivate var leadingKeyframe: Keyframe<ValueType>? = nil
fileprivate var trailingKeyframe: Keyframe<ValueType>? = nil
/// Finds the appropriate Leading and Trailing keyframe index for the given time.
fileprivate func updateSpanIndices(frame: CGFloat) {
guard keyframes.count > 0 else {
leadingIndex = nil
trailingIndex = nil
leadingKeyframe = nil
trailingKeyframe = nil
return
}
// This function searches through the array to find the span of two keyframes
// that contain the current time.
//
// We could use Array.first(where:) but that would search through the entire array
// each frame.
// Instead we track the last used index and search either forwards or
// backwards from there. This reduces the iterations and complexity from
//
// O(n), where n is the length of the sequence to
// O(n), where n is the number of items after or before the last used index.
//
if keyframes.count == 1 {
/// Only one keyframe. Set it as first and move on.
leadingIndex = 0
trailingIndex = nil
leadingKeyframe = keyframes[0]
trailingKeyframe = nil
return
}
/// Sets the initial keyframes. This is often only needed for the first check.
if
leadingIndex == nil,
trailingIndex == nil
{
if frame < keyframes[0].time {
/// Time is before the first keyframe. Set it as the trailing.
trailingIndex = 0
} else {
/// Time is after the first keyframe. Set the keyframe and the trailing.
leadingIndex = 0
trailingIndex = 1
}
}
if
let currentTrailing = trailingIndex,
keyframes[currentTrailing].time <= frame
{
/// Time is after the current span. Iterate forward.
var newLeading = currentTrailing
var keyframeFound = false
while !keyframeFound {
leadingIndex = newLeading
trailingIndex = keyframes.validIndex(newLeading + 1)
guard let trailing = trailingIndex else {
/// We have reached the end of our keyframes. Time is after the last keyframe.
keyframeFound = true
continue
}
if frame < keyframes[trailing].time {
/// Keyframe in current span.
keyframeFound = true
continue
}
/// Advance the array.
newLeading = trailing
}
} else if
let currentLeading = leadingIndex,
frame < keyframes[currentLeading].time
{
/// Time is before the current span. Iterate backwards
var newTrailing = currentLeading
var keyframeFound = false
while !keyframeFound {
leadingIndex = keyframes.validIndex(newTrailing - 1)
trailingIndex = newTrailing
guard let leading = leadingIndex else {
/// We have reached the end of our keyframes. Time is after the last keyframe.
keyframeFound = true
continue
}
if keyframes[leading].time <= frame {
/// Keyframe in current span.
keyframeFound = true
continue
}
/// Step back
newTrailing = leading
}
}
if let keyFrame = leadingIndex {
leadingKeyframe = keyframes[keyFrame]
} else {
leadingKeyframe = nil
}
if let keyFrame = trailingIndex {
trailingKeyframe = keyframes[keyFrame]
} else {
trailingKeyframe = nil
}
}
}
extension Array {
fileprivate func validIndex(_ index: Int) -> Int? {
if 0 <= index, index < endIndex {
return index
}
return nil
}
}
extension ContiguousArray {
fileprivate func validIndex(_ index: Int) -> Int? {
if 0 <= index, index < endIndex {
return index
}
return nil
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Interpolatable/KeyframeInterpolator.swift
|
Swift
|
unknown
| 6,826
|
// Created by Cal Stephens on 7/26/23.
// Copyright © 2023 Airbnb Inc. All rights reserved.
// MARK: - LottieAnimationSource
/// A data source for a Lottie animation.
/// Either a `LottieAnimation` loaded from a `.json` file,
/// or a `DotLottieFile` loaded from a `.lottie` file.
public enum LottieAnimationSource: Sendable {
/// A `LottieAnimation` loaded from a `.json` file
case lottieAnimation(LottieAnimation)
/// A `DotLottieFile` loaded from a `.lottie` file
case dotLottieFile(DotLottieFile)
}
extension LottieAnimationSource {
/// The default animation displayed by this data source
var animation: LottieAnimation? {
switch self {
case .lottieAnimation(let animation):
return animation
case .dotLottieFile:
return dotLottieAnimation?.animation
}
}
/// The `DotLottieFile.Animation`, if this is a dotLottie animation
var dotLottieAnimation: DotLottieFile.Animation? {
switch self {
case .lottieAnimation:
return nil
case .dotLottieFile(let dotLottieFile):
return dotLottieFile.animation()
}
}
}
extension LottieAnimation {
/// This animation represented as a `LottieAnimationSource`
public var animationSource: LottieAnimationSource {
.lottieAnimation(self)
}
}
extension DotLottieFile {
/// This animation represented as a `LottieAnimationSource`
public var animationSource: LottieAnimationSource {
.dotLottieFile(self)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/LottieAnimationSource.swift
|
Swift
|
unknown
| 1,438
|
//
// Shape.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
import CoreGraphics
// MARK: - BezierPath
/// A container that holds instructions for creating a single, unbroken Bezier Path.
struct BezierPath {
// MARK: Lifecycle
/// Initializes a new Bezier Path.
init(startPoint: CurveVertex) {
elements = [PathElement(vertex: startPoint)]
length = 0
closed = false
}
init() {
elements = []
length = 0
closed = false
}
// MARK: Internal
/// The elements of the path
private(set) var elements: [PathElement]
/// If the path is closed or not.
private(set) var closed: Bool
/// The total length of the path.
private(set) var length: CGFloat
mutating func moveToStartPoint(_ vertex: CurveVertex) {
elements = [PathElement(vertex: vertex)]
length = 0
}
mutating func addVertex(_ vertex: CurveVertex) {
guard let previous = elements.last else {
addElement(PathElement(vertex: vertex))
return
}
addElement(previous.pathElementTo(vertex))
}
mutating func addCurve(toPoint: CGPoint, outTangent: CGPoint, inTangent: CGPoint) {
guard let previous = elements.last else { return }
let newVertex = CurveVertex(inTangent, toPoint, toPoint)
updateVertex(
CurveVertex(previous.vertex.inTangent, previous.vertex.point, outTangent),
atIndex: elements.endIndex - 1,
remeasure: false)
addVertex(newVertex)
}
mutating func addLine(toPoint: CGPoint) {
guard let previous = elements.last else { return }
let newVertex = CurveVertex(point: toPoint, inTangentRelative: .zero, outTangentRelative: .zero)
updateVertex(
CurveVertex(previous.vertex.inTangent, previous.vertex.point, previous.vertex.point),
atIndex: elements.endIndex - 1,
remeasure: false)
addVertex(newVertex)
}
mutating func close() {
closed = true
}
mutating func addElement(_ pathElement: PathElement) {
elements.append(pathElement)
length = length + pathElement.length
}
mutating func updateVertex(_ vertex: CurveVertex, atIndex: Int, remeasure: Bool) {
if remeasure {
var newElement: PathElement
if atIndex > 0 {
let previousElement = elements[atIndex - 1]
newElement = previousElement.pathElementTo(vertex)
} else {
newElement = PathElement(vertex: vertex)
}
elements[atIndex] = newElement
if atIndex + 1 < elements.count {
let nextElement = elements[atIndex + 1]
elements[atIndex + 1] = newElement.pathElementTo(nextElement.vertex)
}
} else {
let oldElement = elements[atIndex]
elements[atIndex] = oldElement.updateVertex(newVertex: vertex)
}
}
/// Trims a path fromLength toLength with an offset.
///
/// Length and offset are defined in the length coordinate space.
/// If any argument is outside the range of this path, then it will be looped over the path from finish to start.
///
/// Cutting the curve when fromLength is less than toLength
/// x x x x
/// ~~~~~~~~~~~~~~~ooooooooooooooooooooooooooooooooooooooooooooooooo-------------------
/// |Offset |fromLength toLength| |
///
/// Cutting the curve when from Length is greater than toLength
/// x x x x x
/// oooooooooooooooooo--------------------~~~~~~~~~~~~~~~~ooooooooooooooooooooooooooooo
/// | toLength| |Offset |fromLength |
///
func trim(fromLength: CGFloat, toLength: CGFloat, offsetLength: CGFloat) -> [BezierPath] {
guard elements.count > 1 else {
return []
}
if fromLength == toLength {
return []
}
/// Normalize lengths to the curve length.
var start = (fromLength + offsetLength).truncatingRemainder(dividingBy: length)
var end = (toLength + offsetLength).truncatingRemainder(dividingBy: length)
if start < 0 {
start = length + start
}
if end < 0 {
end = length + end
}
if start == length {
start = 0
}
if end == 0 {
end = length
}
if
start == 0 && end == length ||
start == end ||
start == length && end == 0
{
/// The trim encompasses the entire path. Return.
return [self]
}
if start > end {
// Start is greater than end. Two paths are returned.
return trimPathAtLengths(positions: [(start: 0, end: end), (start: start, end: length)])
}
return trimPathAtLengths(positions: [(start: start, end: end)])
}
// MARK: Private
private func trimPathAtLengths(positions: [(start: CGFloat, end: CGFloat)]) -> [BezierPath] {
guard positions.count > 0 else {
return []
}
var remainingPositions = positions
var trim = remainingPositions.remove(at: 0)
var paths = [BezierPath]()
var runningLength: CGFloat = 0
var finishedTrimming = false
var pathElements = elements
var currentPath = BezierPath()
var i = 0
while !finishedTrimming {
if pathElements.count <= i {
/// Do this for rounding errors
paths.append(currentPath)
finishedTrimming = true
continue
}
/// Loop through and add elements within start->end range.
/// Get current element
let element = pathElements[i]
/// Calculate new running length.
let newLength = runningLength + element.length
if newLength < trim.start {
/// Element is not included in the trim, continue.
runningLength = newLength
i = i + 1
/// Increment index, we are done with this element.
continue
}
if newLength == trim.start {
/// Current element IS the start element.
/// For start we want to add a zero length element.
currentPath.moveToStartPoint(element.vertex)
runningLength = newLength
i = i + 1
/// Increment index, we are done with this element.
continue
}
if runningLength < trim.start, trim.start < newLength, currentPath.elements.count == 0 {
/// The start of the trim is between this element and the previous, trim.
/// Get previous element.
let previousElement = pathElements[i - 1]
/// Trim it
let trimLength = trim.start - runningLength
let trimResults = element.splitElementAtPosition(fromElement: previousElement, atLength: trimLength)
/// Add the right span start.
currentPath.moveToStartPoint(trimResults.rightSpan.start.vertex)
pathElements[i] = trimResults.rightSpan.end
pathElements[i - 1] = trimResults.rightSpan.start
runningLength = runningLength + trimResults.leftSpan.end.length
/// Dont increment index or the current length, the end of this path can be within this span.
continue
}
if trim.start < newLength, newLength < trim.end {
/// Element lies within the trim span.
currentPath.addElement(element)
runningLength = newLength
i = i + 1
continue
}
if newLength == trim.end {
/// Element is the end element.
/// The element could have a new length if it's added right after the start node.
currentPath.addElement(element)
/// We are done with this span.
runningLength = newLength
i = i + 1
/// Allow the path to be finalized.
/// Fall through to finalize path and move to next position
}
if runningLength < trim.end, trim.end < newLength {
/// New element must be cut for end.
/// Get previous element.
let previousElement = pathElements[i - 1]
/// Trim it
let trimLength = trim.end - runningLength
let trimResults = element.splitElementAtPosition(fromElement: previousElement, atLength: trimLength)
/// Add the left span end.
currentPath.updateVertex(trimResults.leftSpan.start.vertex, atIndex: currentPath.elements.count - 1, remeasure: false)
currentPath.addElement(trimResults.leftSpan.end)
pathElements[i] = trimResults.rightSpan.end
pathElements[i - 1] = trimResults.rightSpan.start
runningLength = runningLength + trimResults.leftSpan.end.length
/// Dont increment index or the current length, the start of the next path can be within this span.
/// We are done with this span.
/// Allow the path to be finalized.
/// Fall through to finalize path and move to next position
}
paths.append(currentPath)
currentPath = BezierPath()
if remainingPositions.count > 0 {
trim = remainingPositions.remove(at: 0)
} else {
finishedTrimming = true
}
}
return paths
}
}
// MARK: Codable
extension BezierPath: Codable {
// MARK: Lifecycle
init(from decoder: Decoder) throws {
let container: KeyedDecodingContainer<BezierPath.CodingKeys>
if let keyedContainer = try? decoder.container(keyedBy: BezierPath.CodingKeys.self) {
container = keyedContainer
} else {
var unkeyedContainer = try decoder.unkeyedContainer()
container = try unkeyedContainer.nestedContainer(keyedBy: BezierPath.CodingKeys.self)
}
closed = try container.decodeIfPresent(Bool.self, forKey: .closed) ?? true
var vertexContainer = try container.nestedUnkeyedContainer(forKey: .vertices)
var inPointsContainer = try container.nestedUnkeyedContainer(forKey: .inPoints)
var outPointsContainer = try container.nestedUnkeyedContainer(forKey: .outPoints)
guard vertexContainer.count == inPointsContainer.count, inPointsContainer.count == outPointsContainer.count else {
/// Will throw an error if vertex, inpoints, and outpoints are not the same length.
/// This error is to be expected.
throw DecodingError.dataCorruptedError(
forKey: CodingKeys.vertices,
in: container,
debugDescription: "Vertex data does not match In Tangents and Out Tangents")
}
guard let count = vertexContainer.count, count > 0 else {
length = 0
elements = []
return
}
var decodedElements = [PathElement]()
/// Create first point
let firstVertex = CurveVertex(
point: try vertexContainer.decode(CGPoint.self),
inTangentRelative: try inPointsContainer.decode(CGPoint.self),
outTangentRelative: try outPointsContainer.decode(CGPoint.self))
var previousElement = PathElement(vertex: firstVertex)
decodedElements.append(previousElement)
var totalLength: CGFloat = 0
while !vertexContainer.isAtEnd {
/// Get the next vertex data.
let vertex = CurveVertex(
point: try vertexContainer.decode(CGPoint.self),
inTangentRelative: try inPointsContainer.decode(CGPoint.self),
outTangentRelative: try outPointsContainer.decode(CGPoint.self))
let pathElement = previousElement.pathElementTo(vertex)
decodedElements.append(pathElement)
previousElement = pathElement
totalLength = totalLength + pathElement.length
}
if closed {
let closeElement = previousElement.pathElementTo(firstVertex)
decodedElements.append(closeElement)
totalLength = totalLength + closeElement.length
}
length = totalLength
elements = decodedElements
}
// MARK: Internal
/// The BezierPath container is encoded and decoded from the JSON format
/// that defines points for a lottie animation.
///
/// {
/// "c" = Bool
/// "i" = [[Double]],
/// "o" = [[Double]],
/// "v" = [[Double]]
/// }
///
enum CodingKeys: String, CodingKey {
case closed = "c"
case inPoints = "i"
case outPoints = "o"
case vertices = "v"
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: BezierPath.CodingKeys.self)
try container.encode(closed, forKey: .closed)
var vertexContainer = container.nestedUnkeyedContainer(forKey: .vertices)
var inPointsContainer = container.nestedUnkeyedContainer(forKey: .inPoints)
var outPointsContainer = container.nestedUnkeyedContainer(forKey: .outPoints)
/// If closed path, ignore the final element.
let finalIndex = closed ? elements.endIndex - 1 : elements.endIndex
for i in 0..<finalIndex {
let element = elements[i]
try vertexContainer.encode(element.vertex.point)
try inPointsContainer.encode(element.vertex.inTangentRelative)
try outPointsContainer.encode(element.vertex.outTangentRelative)
}
}
}
// MARK: AnyInitializable
extension BezierPath: AnyInitializable {
init(value: Any) throws {
var pathDictionary: [String: Any]
if
let array = value as? [[String: Any]],
let firstDictionary = array.first
{
pathDictionary = firstDictionary
} else if let dictionary = value as? [String: Any] {
pathDictionary = dictionary
} else {
throw InitializableError.invalidInput()
}
closed = (try? pathDictionary.value(for: CodingKeys.closed)) ?? true
var vertexDictionaries: [Any] = try pathDictionary.value(for: CodingKeys.vertices)
var inPointsDictionaries: [Any] = try pathDictionary.value(for: CodingKeys.inPoints)
var outPointsDictionaries: [Any] = try pathDictionary.value(for: CodingKeys.outPoints)
guard
vertexDictionaries.count == inPointsDictionaries.count,
inPointsDictionaries.count == outPointsDictionaries.count
else {
throw InitializableError.invalidInput()
}
guard vertexDictionaries.count > 0 else {
length = 0
elements = []
return
}
var decodedElements = [PathElement]()
let firstVertexDictionary = vertexDictionaries.removeFirst()
let firstInPointsDictionary = inPointsDictionaries.removeFirst()
let firstOutPointsDictionary = outPointsDictionaries.removeFirst()
let firstVertex = CurveVertex(
point: try CGPoint(value: firstVertexDictionary),
inTangentRelative: try CGPoint(value: firstInPointsDictionary),
outTangentRelative: try CGPoint(value: firstOutPointsDictionary))
var previousElement = PathElement(vertex: firstVertex)
decodedElements.append(previousElement)
var totalLength: CGFloat = 0
while vertexDictionaries.count > 0 {
let vertexDictionary = vertexDictionaries.removeFirst()
let inPointsDictionary = inPointsDictionaries.removeFirst()
let outPointsDictionary = outPointsDictionaries.removeFirst()
let vertex = CurveVertex(
point: try CGPoint(value: vertexDictionary),
inTangentRelative: try CGPoint(value: inPointsDictionary),
outTangentRelative: try CGPoint(value: outPointsDictionary))
let pathElement = previousElement.pathElementTo(vertex)
decodedElements.append(pathElement)
previousElement = pathElement
totalLength = totalLength + pathElement.length
}
if closed {
let closeElement = previousElement.pathElementTo(firstVertex)
decodedElements.append(closeElement)
totalLength = totalLength + closeElement.length
}
length = totalLength
elements = decodedElements
}
}
extension BezierPath {
func cgPath() -> CGPath {
let cgPath = CGMutablePath()
var previousElement: PathElement?
for element in elements {
if let previous = previousElement {
if previous.vertex.outTangentRelative.isZero, element.vertex.inTangentRelative.isZero {
cgPath.addLine(to: element.vertex.point)
} else {
cgPath.addCurve(to: element.vertex.point, control1: previous.vertex.outTangent, control2: element.vertex.inTangent)
}
} else {
cgPath.move(to: element.vertex.point)
}
previousElement = element
}
if closed {
cgPath.closeSubpath()
}
return cgPath
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Primitives/BezierPath.swift
|
Swift
|
unknown
| 15,973
|
//
// BezierPathRoundExtension.swift
// Lottie
//
// Created by Duolingo on 11/1/22.
//
import CoreGraphics
import Foundation
// Adapted to Swift from lottie-web & lottie-android:
// Rounded corner algorithm:
// Iterate through each vertex.
// If a vertex is a sharp corner, it rounds it.
// If a vertex has control points, it is already rounded, so it does nothing.
//
// To round a vertex:
// Split the vertex into two.
// Move vertex 1 directly towards the previous vertex.
// Set vertex 1's in control point to itself so it is not rounded on that side.
// Extend vertex 1's out control point towards the original vertex.
//
// Repeat for vertex 2:
// Move vertex 2 directly towards the next vertex.
// Set vertex 2's out point to itself so it is not rounded on that side.
// Extend vertex 2's in control point towards the original vertex.
//
// The distance that the vertices and control points are moved are relative to the
// shape's vertex distances and the roundedness set in the animation.
extension CompoundBezierPath {
// Round corners of a compound bezier
func roundCorners(radius: CGFloat) -> CompoundBezierPath {
var newPaths = [BezierPath]()
for path in paths {
newPaths.append(
path.roundCorners(radius: radius))
}
return CompoundBezierPath(paths: newPaths)
}
}
extension BezierPath {
// Computes a new `BezierPath` with each corner rounded based on the given `radius`
func roundCorners(radius: CGFloat) -> BezierPath {
var newPath = BezierPath()
var uniquePath = BezierPath()
var currentVertex: CurveVertex
var closestVertex: CurveVertex
var distance: CGFloat
var newPosPerc: CGFloat
var closestIndex: Int
var iX: CGFloat
var iY: CGFloat
var vX: CGFloat
var vY: CGFloat
var oX: CGFloat
var oY: CGFloat
var startIndex = 0
let TANGENT_LENGTH = 0.5519
// If start and end are the same we close the path
if
elements[0].vertex.point == elements[elements.count - 1].vertex.point,
elements[0].vertex.inTangent == elements[elements.count - 1].vertex.inTangent,
elements[0].vertex.outTangent == elements[elements.count - 1].vertex.outTangent
{
startIndex = 1
newPath.close()
}
guard elements.count - startIndex > 1 else {
return self
}
for i in startIndex..<elements.count {
uniquePath.addVertex(elements[i].vertex)
}
var pathHasRoundedCorner = false
for elementIndex in 0..<uniquePath.elements.count {
currentVertex = uniquePath.elements[elementIndex].vertex
guard
currentVertex.point.x == currentVertex.outTangent.x,
currentVertex.point.y == currentVertex.outTangent.y,
currentVertex.point.x == currentVertex.inTangent.x,
currentVertex.point.y == currentVertex.inTangent.y
else {
newPath.addVertex(currentVertex)
continue
}
// Track whether or not this path has at least one rounded corner
pathHasRoundedCorner = true
// Do not round start and end if not closed
if !newPath.closed, elementIndex == 0 || elementIndex == uniquePath.elements.count - 1 {
newPath.addVertex(currentVertex)
} else {
closestIndex = elementIndex - 1
if closestIndex < 0 {
closestIndex = uniquePath.elements.count - 1
}
closestVertex = uniquePath.elements[closestIndex].vertex
distance = currentVertex.point.distanceTo(closestVertex.point)
newPosPerc = distance != 0 ? min(distance / 2, radius) / distance : 0
iX = currentVertex.point.x + (closestVertex.point.x - currentVertex.point.x) * newPosPerc
vX = iX
iY = currentVertex.point.y - (currentVertex.point.y - closestVertex.point.y) * newPosPerc
vY = iY
oX = vX - (vX - currentVertex.point.x) * TANGENT_LENGTH
oY = vY - (vY - currentVertex.point.y) * TANGENT_LENGTH
newPath.addVertex(
CurveVertex(
CGPoint(x: iX, y: iY),
CGPoint(x: vX, y: vY),
CGPoint(x: oX, y: oY)))
closestIndex = (elementIndex + 1) % uniquePath.elements.count
closestVertex = uniquePath.elements[closestIndex].vertex
distance = currentVertex.point.distanceTo(closestVertex.point)
newPosPerc = distance != 0 ? min(distance / 2, radius) / distance : 0
oX = currentVertex.point.x + (closestVertex.point.x - currentVertex.point.x) * newPosPerc
vX = oX
oY = currentVertex.point.y + (closestVertex.point.y - currentVertex.point.y) * newPosPerc
vY = oY
iX = vX - (vX - currentVertex.point.x) * TANGENT_LENGTH
iY = vY - (vY - currentVertex.point.y) * TANGENT_LENGTH
newPath.addVertex(
CurveVertex(
CGPoint(x: iX, y: iY),
CGPoint(x: vX, y: vY),
CGPoint(x: oX, y: oY)))
}
}
// If we didn't need to apply the corner radius to any of the corners,
// just use the original given path instead of modifying it.
if !pathHasRoundedCorner {
return self
}
return newPath
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Primitives/BezierPathRoundExtension.swift
|
Swift
|
unknown
| 5,163
|
//
// CGPointExtension.swift
// Lottie
//
// Created by Marcelo Fabri on 5/5/22.
//
import CoreGraphics
extension CGPoint: AnyInitializable {
// MARK: Lifecycle
init(value: Any) throws {
if let dictionary = value as? [String: CGFloat] {
let x: CGFloat = try dictionary.value(for: CodingKeys.x)
let y: CGFloat = try dictionary.value(for: CodingKeys.y)
self.init(x: x, y: y)
} else if
let array = value as? [CGFloat],
array.count > 1
{
self.init(x: array[0], y: array[1])
} else {
throw InitializableError.invalidInput()
}
}
// MARK: Private
private enum CodingKeys: String {
case x
case y
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Primitives/CGPointExtension.swift
|
Swift
|
unknown
| 683
|
//
// LottieColor.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/14/19.
//
import CoreGraphics
// MARK: - LottieColor + Codable
extension LottieColor: Codable {
// MARK: Lifecycle
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
var r1: Double
if !container.isAtEnd {
r1 = try container.decode(Double.self)
} else {
r1 = 0
}
var g1: Double
if !container.isAtEnd {
g1 = try container.decode(Double.self)
} else {
g1 = 0
}
var b1: Double
if !container.isAtEnd {
b1 = try container.decode(Double.self)
} else {
b1 = 0
}
if r1 > 1, g1 > 1, b1 > 1 {
r1 = r1 / 255
g1 = g1 / 255
b1 = b1 / 255
}
r = r1
g = g1
b = b1
// The Lottie JSON schema supports alpha values in theory, as the fourth value in this array.
// We intentionally do not support this, though, for consistency with Lottie on other platforms.
a = 1
}
// MARK: Public
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(r)
try container.encode(g)
try container.encode(b)
try container.encode(a)
}
}
// MARK: - LottieColor + AnyInitializable
extension LottieColor: AnyInitializable {
init(value: Any) throws {
guard var array = value as? [Double] else {
throw InitializableError.invalidInput()
}
var r: Double = array.count > 0 ? array.removeFirst() : 0
var g: Double = array.count > 0 ? array.removeFirst() : 0
var b: Double = array.count > 0 ? array.removeFirst() : 0
if r > 1, g > 1, b > 1 {
r /= 255
g /= 255
b /= 255
}
self.r = r
self.g = g
self.b = b
// The Lottie JSON schema supports alpha values in theory, as the fourth value in this array.
// We intentionally do not support this, though, for consistency with Lottie on other platforms.
a = 1
}
}
extension LottieColor {
static var clearColor: CGColor {
.rgba(0, 0, 0, 0)
}
var cgColorValue: CGColor {
.rgba(CGFloat(r), CGFloat(g), CGFloat(b), CGFloat(a))
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Primitives/ColorExtension.swift
|
Swift
|
unknown
| 2,182
|
//
// CompoundBezierPath.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/14/19.
//
import CoreGraphics
import Foundation
/// A collection of BezierPath objects that can be trimmed and added.
///
struct CompoundBezierPath {
// MARK: Lifecycle
init() {
paths = []
length = 0
}
init(path: BezierPath) {
paths = [path]
length = path.length
}
init(paths: [BezierPath], length: CGFloat) {
self.paths = paths
self.length = length
}
init(paths: [BezierPath]) {
self.paths = paths
var l: CGFloat = 0
for path in paths {
l = l + path.length
}
length = l
}
// MARK: Internal
let paths: [BezierPath]
let length: CGFloat
func addPath(path: BezierPath) -> CompoundBezierPath {
var newPaths = paths
newPaths.append(path)
return CompoundBezierPath(paths: newPaths, length: length + path.length)
}
func combine(_ compoundBezier: CompoundBezierPath) -> CompoundBezierPath {
var newPaths = paths
newPaths.append(contentsOf: compoundBezier.paths)
return CompoundBezierPath(paths: newPaths, length: length + compoundBezier.length)
}
func trim(fromPosition: CGFloat, toPosition: CGFloat, offset: CGFloat, trimSimultaneously: Bool) -> CompoundBezierPath {
if fromPosition == toPosition {
return CompoundBezierPath()
}
if trimSimultaneously {
/// Trim each path individually.
var newPaths = [BezierPath]()
for path in paths {
newPaths.append(contentsOf: path.trim(
fromLength: fromPosition * path.length,
toLength: toPosition * path.length,
offsetLength: offset * path.length))
}
return CompoundBezierPath(paths: newPaths)
}
/// Normalize lengths to the curve length.
var startPosition = (fromPosition + offset).truncatingRemainder(dividingBy: 1)
var endPosition = (toPosition + offset).truncatingRemainder(dividingBy: 1)
if startPosition < 0 {
startPosition = 1 + startPosition
}
if endPosition < 0 {
endPosition = 1 + endPosition
}
if startPosition == 1 {
startPosition = 0
}
if endPosition == 0 {
endPosition = 1
}
if
startPosition == 0 && endPosition == 1 ||
startPosition == endPosition ||
startPosition == 1 && endPosition == 0
{
/// The trim encompasses the entire path. Return.
return self
}
var positions: [(start: CGFloat, end: CGFloat)]
if endPosition < startPosition {
positions = [
(start: 0, end: endPosition * length),
(start: startPosition * length, end: length),
]
} else {
positions = [(start: startPosition * length, end: endPosition * length)]
}
var compoundPath = CompoundBezierPath()
var trim = positions.remove(at: 0)
var pathStartPosition: CGFloat = 0
var finishedTrimming = false
var i = 0
while !finishedTrimming {
if paths.count <= i {
/// Rounding errors
finishedTrimming = true
continue
}
let path = paths[i]
let pathEndPosition = pathStartPosition + path.length
if pathEndPosition < trim.start {
/// Path is not included in the trim, continue.
pathStartPosition = pathEndPosition
i = i + 1
continue
} else if trim.start <= pathStartPosition, pathEndPosition <= trim.end {
/// Full Path is inside of trim. Add full path.
compoundPath = compoundPath.addPath(path: path)
} else {
if
let trimPath = path.trim(
fromLength: trim.start > pathStartPosition ? (trim.start - pathStartPosition) : 0,
toLength: trim.end < pathEndPosition ? (trim.end - pathStartPosition) : path.length,
offsetLength: 0).first
{
compoundPath = compoundPath.addPath(path: trimPath)
}
}
if trim.end <= pathEndPosition {
/// We are done with the current trim.
/// Advance trim but remain on the same path in case the next trim overlaps it.
if positions.count > 0 {
trim = positions.remove(at: 0)
} else {
finishedTrimming = true
}
} else {
pathStartPosition = pathEndPosition
i = i + 1
}
}
return compoundPath
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Primitives/CompoundBezierPath.swift
|
Swift
|
unknown
| 4,316
|
//
// CurveVertex.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/11/19.
//
import CoreGraphics
import Foundation
/// A single vertex with an in and out tangent
struct CurveVertex {
// MARK: Lifecycle
/// Initializes a curve point with absolute values
init(_ inTangent: CGPoint, _ point: CGPoint, _ outTangent: CGPoint) {
self.point = point
self.inTangent = inTangent
self.outTangent = outTangent
}
/// Initializes a curve point with relative values
init(point: CGPoint, inTangentRelative: CGPoint, outTangentRelative: CGPoint) {
self.point = point
inTangent = point.add(inTangentRelative)
outTangent = point.add(outTangentRelative)
}
/// Initializes a curve point with absolute values
init(point: CGPoint, inTangent: CGPoint, outTangent: CGPoint) {
self.point = point
self.inTangent = inTangent
self.outTangent = outTangent
}
// MARK: Internal
let point: CGPoint
let inTangent: CGPoint
let outTangent: CGPoint
var inTangentRelative: CGPoint {
inTangent.subtract(point)
}
var outTangentRelative: CGPoint {
outTangent.subtract(point)
}
func reversed() -> CurveVertex {
CurveVertex(point: point, inTangent: outTangent, outTangent: inTangent)
}
func translated(_ translation: CGPoint) -> CurveVertex {
CurveVertex(point: point + translation, inTangent: inTangent + translation, outTangent: outTangent + translation)
}
/// Trims a path defined by two Vertices at a specific position, from 0 to 1
///
/// The path can be visualized below.
///
/// F is fromVertex.
/// V is the vertex of the receiver.
/// P is the position from 0-1.
/// O is the outTangent of fromVertex.
/// F====O=========P=======I====V
///
/// After trimming the curve can be visualized below.
///
/// S is the returned Start vertex.
/// E is the returned End vertex.
/// T is the trim point.
/// TI and TO are the new tangents for the trimPoint
/// NO and NI are the new tangents for the startPoint and endPoints
/// S==NO=========TI==T==TO=======NI==E
func splitCurve(toVertex: CurveVertex, position: CGFloat) ->
(start: CurveVertex, trimPoint: CurveVertex, end: CurveVertex)
{
/// If position is less than or equal to 0, trim at start.
if position <= 0 {
return (
start: CurveVertex(point: point, inTangentRelative: inTangentRelative, outTangentRelative: .zero),
trimPoint: CurveVertex(point: point, inTangentRelative: .zero, outTangentRelative: outTangentRelative),
end: toVertex)
}
/// If position is greater than or equal to 1, trim at end.
if position >= 1 {
return (
start: self,
trimPoint: CurveVertex(
point: toVertex.point,
inTangentRelative: toVertex.inTangentRelative,
outTangentRelative: .zero),
end: CurveVertex(
point: toVertex.point,
inTangentRelative: .zero,
outTangentRelative: toVertex.outTangentRelative))
}
if outTangentRelative.isZero, toVertex.inTangentRelative.isZero {
/// If both tangents are zero, then span to be trimmed is a straight line.
let trimPoint = point.interpolate(to: toVertex.point, amount: position)
return (
start: self,
trimPoint: CurveVertex(point: trimPoint, inTangentRelative: .zero, outTangentRelative: .zero),
end: toVertex)
}
/// Cutting by amount gives incorrect length....
/// One option is to cut by a stride until it gets close then edge it down.
/// Measuring a percentage of the spans does not equal the same as measuring a percentage of length.
/// This is where the historical trim path bugs come from.
let a = point.interpolate(to: outTangent, amount: position)
let b = outTangent.interpolate(to: toVertex.inTangent, amount: position)
let c = toVertex.inTangent.interpolate(to: toVertex.point, amount: position)
let d = a.interpolate(to: b, amount: position)
let e = b.interpolate(to: c, amount: position)
let f = d.interpolate(to: e, amount: position)
return (
start: CurveVertex(point: point, inTangent: inTangent, outTangent: a),
trimPoint: CurveVertex(point: f, inTangent: d, outTangent: e),
end: CurveVertex(point: toVertex.point, inTangent: c, outTangent: toVertex.outTangent))
}
/// Trims a curve of a known length to a specific length and returns the points.
///
/// There is not a performant yet accurate way to cut a curve to a specific length.
/// This calls splitCurve(toVertex: position:) to split the curve and then measures
/// the length of the new curve. The function then iterates through the samples,
/// adjusting the position of the cut for a more precise cut.
/// Usually a single iteration is enough to get within 0.5 points of the desired
/// length.
///
/// This function should probably live in PathElement, since it deals with curve
/// lengths.
func trimCurve(toVertex: CurveVertex, atLength: CGFloat, curveLength: CGFloat, maxSamples: Int, accuracy: CGFloat = 1) ->
(start: CurveVertex, trimPoint: CurveVertex, end: CurveVertex)
{
var currentPosition = atLength / curveLength
var results = splitCurve(toVertex: toVertex, position: currentPosition)
if maxSamples == 0 {
return results
}
for _ in 1...maxSamples {
let length = results.start.distanceTo(results.trimPoint)
let lengthDiff = atLength - length
/// Check if length is correct.
if lengthDiff < accuracy {
return results
}
let diffPosition = max(min((currentPosition / length) * lengthDiff, currentPosition * 0.5), currentPosition * -0.5)
currentPosition = diffPosition + currentPosition
results = splitCurve(toVertex: toVertex, position: currentPosition)
}
return results
}
/// The distance from the receiver to the provided vertex.
///
/// For lines (zeroed tangents) the distance between the two points is measured.
/// For curves the curve is iterated over by sample count and the points are measured.
/// This is ~99% accurate at a sample count of 30
func distanceTo(_ toVertex: CurveVertex, sampleCount: Int = 25) -> CGFloat {
if outTangentRelative.isZero, toVertex.inTangentRelative.isZero {
/// Return a linear distance.
return point.distanceTo(toVertex.point)
}
var distance: CGFloat = 0
var previousPoint = point
for i in 0..<sampleCount {
let pointOnCurve = splitCurve(toVertex: toVertex, position: CGFloat(i) / CGFloat(sampleCount)).trimPoint
distance = distance + previousPoint.distanceTo(pointOnCurve.point)
previousPoint = pointOnCurve.point
}
distance = distance + previousPoint.distanceTo(toVertex.point)
return distance
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Primitives/CurveVertex.swift
|
Swift
|
unknown
| 6,785
|
//
// PathElement.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/11/19.
//
import CoreGraphics
import Foundation
/// A path section, containing one point and its length to the previous point.
///
/// The relationship between this path element and the previous is implicit.
/// Ideally a path section would be defined by two vertices and a length.
/// We don't do this however, as it would effectively double the memory footprint
/// of path data.
///
struct PathElement {
// MARK: Lifecycle
/// Initializes a new path with length of 0
init(vertex: CurveVertex) {
length = 0
self.vertex = vertex
}
/// Initializes a new path with length
private init(length: CGFloat, vertex: CurveVertex) {
self.length = length
self.vertex = vertex
}
// MARK: Internal
/// The absolute Length of the path element.
let length: CGFloat
/// The vertex of the element
let vertex: CurveVertex
/// Returns a new path element define the span from the receiver to the new vertex.
func pathElementTo(_ toVertex: CurveVertex) -> PathElement {
PathElement(length: vertex.distanceTo(toVertex), vertex: toVertex)
}
func updateVertex(newVertex: CurveVertex) -> PathElement {
PathElement(length: length, vertex: newVertex)
}
/// Splits an element span defined by the receiver and fromElement to a position 0-1
func splitElementAtPosition(fromElement: PathElement, atLength: CGFloat) ->
(leftSpan: (start: PathElement, end: PathElement), rightSpan: (start: PathElement, end: PathElement))
{
/// Trim the span. Start and trim go into the first, trim and end go into second.
let trimResults = fromElement.vertex.trimCurve(toVertex: vertex, atLength: atLength, curveLength: length, maxSamples: 3)
/// Create the elements for the break
let spanAStart = PathElement(
length: fromElement.length,
vertex: CurveVertex(
point: fromElement.vertex.point,
inTangent: fromElement.vertex.inTangent,
outTangent: trimResults.start.outTangent))
/// Recalculating the length here is a waste as the trimCurve function also accurately calculates this length.
let spanAEnd = spanAStart.pathElementTo(trimResults.trimPoint)
let spanBStart = PathElement(vertex: trimResults.trimPoint)
let spanBEnd = spanBStart.pathElementTo(trimResults.end)
return (
leftSpan: (start: spanAStart, end: spanAEnd),
rightSpan: (start: spanBStart, end: spanBEnd))
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Primitives/PathElement.swift
|
Swift
|
unknown
| 2,475
|
// Copyright (C) 2008 Apple Inc. All Rights Reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import CoreGraphics
import Foundation
/// Defines a cubic-bezier where the endpoints are (0, 0) and (1, 1)
///
/// The main use case is computing the progress of an animation at a given percent completion. For instance,
/// for a linear animation, the expected progress at `0.5` is `0.5`.
///
/// - Note: This is a Swift port of [Apple's WebKit code](
/// http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h
/// )
///
struct UnitBezier {
// MARK: Lifecycle
init(controlPoint1: CGPoint, controlPoint2: CGPoint) {
cx = 3.0 * controlPoint1.x
bx = 3.0 * (controlPoint2.x - controlPoint1.x) - cx
ax = 1.0 - cx - bx
cy = 3.0 * controlPoint1.y
by = 3.0 * (controlPoint2.y - controlPoint1.y) - cy
ay = 1.0 - cy - by
}
// MARK: Internal
/// Computes the progress `y` value for a given `x` value
func value(for x: CGFloat, epsilon: CGFloat) -> CGFloat {
sampleCurveY(solveCurveX(x, epsilon: epsilon))
}
// MARK: Private
private let ax: CGFloat
private let bx: CGFloat
private let cx: CGFloat
private let ay: CGFloat
private let by: CGFloat
private let cy: CGFloat
/// Compute `x(t)` for a given `t`
private func sampleCurveX(_ t: CGFloat) -> CGFloat {
// `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.
((ax * t + bx) * t + cx) * t
}
/// Compute `y(t)` for a given `t`
private func sampleCurveY(_ t: CGFloat) -> CGFloat {
((ay * t + by) * t + cy) * t
}
/// Compute `x'(t)` for a given `t`
private func sampleCurveDerivativeX(_ t: CGFloat) -> CGFloat {
(3.0 * ax * t + 2.0 * bx) * t + cx
}
/// Given an `x` value solve for the parametric value `t`
private func solveCurveX(_ x: CGFloat, epsilon: CGFloat) -> CGFloat {
var t0, t1, t2, x2, d2: CGFloat
// First try a few iterations of Newton-Raphson -- normally very fast.
t2 = x
for _ in 0..<8 {
x2 = sampleCurveX(t2) - x
guard abs(x2) >= epsilon else { return t2 }
d2 = sampleCurveDerivativeX(t2)
guard abs(d2) >= 1e-6 else { break }
t2 = t2 - x2 / d2
}
// Fall back to the bisection method for reliability.
t0 = 0.0
t1 = 1.0
t2 = x
guard t2 >= t0 else { return t0 }
guard t2 <= t1 else { return t1 }
while t0 < t1 {
x2 = sampleCurveX(t2)
guard abs(x2 - x) >= epsilon else { return t2 }
if x > x2 {
t0 = t2
} else {
t1 = t2
}
t2 = (t1 - t0) * 0.5 + t0
}
return t2
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Primitives/UnitBezier.swift
|
Swift
|
unknown
| 3,830
|
//
// Vector.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/7/19.
//
import CoreGraphics
import Foundation
import QuartzCore
// MARK: - LottieVector1D + Codable
/// Single value container. Needed because lottie sometimes wraps a Double in an array.
extension LottieVector1D: Codable {
// MARK: Lifecycle
public init(from decoder: Decoder) throws {
/// Try to decode an array of doubles
do {
var container = try decoder.unkeyedContainer()
value = try container.decode(Double.self)
} catch {
value = try decoder.singleValueContainer().decode(Double.self)
}
}
// MARK: Public
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(value)
}
// MARK: Internal
var cgFloatValue: CGFloat {
CGFloat(value)
}
}
// MARK: - LottieVector1D + AnyInitializable
extension LottieVector1D: AnyInitializable {
init(value: Any) throws {
if
let array = value as? [Double],
let double = array.first
{
self.value = double
} else if let double = value as? Double {
self.value = double
} else {
throw InitializableError.invalidInput()
}
}
}
extension Double {
var vectorValue: LottieVector1D {
LottieVector1D(self)
}
}
// MARK: - LottieVector2D
/// Needed for decoding json {x: y:} to a CGPoint
public struct LottieVector2D: Codable, Hashable, Sendable {
// MARK: Lifecycle
init(x: Double, y: Double) {
self.x = x
self.y = y
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: LottieVector2D.CodingKeys.self)
do {
let xValue: [Double] = try container.decode([Double].self, forKey: .x)
x = xValue[0]
} catch {
x = try container.decode(Double.self, forKey: .x)
}
do {
let yValue: [Double] = try container.decode([Double].self, forKey: .y)
y = yValue[0]
} catch {
y = try container.decode(Double.self, forKey: .y)
}
}
// MARK: Public
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: LottieVector2D.CodingKeys.self)
try container.encode(x, forKey: .x)
try container.encode(y, forKey: .y)
}
// MARK: Internal
var x: Double
var y: Double
var pointValue: CGPoint {
CGPoint(x: x, y: y)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case x
case y
}
}
// MARK: AnyInitializable
extension LottieVector2D: AnyInitializable {
init(value: Any) throws {
guard let dictionary = value as? [String: Any] else {
throw InitializableError.invalidInput()
}
if
let array = dictionary[CodingKeys.x.rawValue] as? [Double],
let double = array.first
{
x = double
} else if let double = dictionary[CodingKeys.x.rawValue] as? Double {
x = double
} else {
throw InitializableError.invalidInput()
}
if
let array = dictionary[CodingKeys.y.rawValue] as? [Double],
let double = array.first
{
y = double
} else if let double = dictionary[CodingKeys.y.rawValue] as? Double {
y = double
} else {
throw InitializableError.invalidInput()
}
}
}
extension CGPoint {
var vector2dValue: LottieVector2D {
LottieVector2D(x: Double(x), y: Double(y))
}
}
// MARK: - LottieVector3D + Codable
/// A three dimensional vector.
/// These vectors are encoded and decoded from [Double]
extension LottieVector3D: Codable {
// MARK: Lifecycle
init(x: CGFloat, y: CGFloat, z: CGFloat) {
self.x = Double(x)
self.y = Double(y)
self.z = Double(z)
}
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
if !container.isAtEnd {
x = try container.decode(Double.self)
} else {
x = 0
}
if !container.isAtEnd {
y = try container.decode(Double.self)
} else {
y = 0
}
if !container.isAtEnd {
z = try container.decode(Double.self)
} else {
z = 0
}
}
// MARK: Public
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(x)
try container.encode(y)
try container.encode(z)
}
}
// MARK: - LottieVector3D + AnyInitializable
extension LottieVector3D: AnyInitializable {
init(value: Any) throws {
guard var array = value as? [Double] else {
throw InitializableError.invalidInput()
}
x = array.count > 0 ? array.removeFirst() : 0
y = array.count > 0 ? array.removeFirst() : 0
z = array.count > 0 ? array.removeFirst() : 0
}
}
extension LottieVector3D {
public var pointValue: CGPoint {
CGPoint(x: x, y: y)
}
public var sizeValue: CGSize {
CGSize(width: x, height: y)
}
}
extension CGPoint {
var vector3dValue: LottieVector3D {
LottieVector3D(x: x, y: y, z: 0)
}
}
extension CGSize {
var vector3dValue: LottieVector3D {
LottieVector3D(x: width, y: height, z: 1)
}
}
extension CATransform3D {
enum Axis {
case x, y, z
}
static func makeSkew(skew: CGFloat, skewAxis: CGFloat) -> CATransform3D {
let mCos = cos(skewAxis.toRadians())
let mSin = sin(skewAxis.toRadians())
let aTan = tan(skew.toRadians())
let transform1 = CATransform3D(
m11: mCos,
m12: mSin,
m13: 0,
m14: 0,
m21: -mSin,
m22: mCos,
m23: 0,
m24: 0,
m31: 0,
m32: 0,
m33: 1,
m34: 0,
m41: 0,
m42: 0,
m43: 0,
m44: 1)
let transform2 = CATransform3D(
m11: 1,
m12: 0,
m13: 0,
m14: 0,
m21: aTan,
m22: 1,
m23: 0,
m24: 0,
m31: 0,
m32: 0,
m33: 1,
m34: 0,
m41: 0,
m42: 0,
m43: 0,
m44: 1)
let transform3 = CATransform3D(
m11: mCos,
m12: -mSin,
m13: 0,
m14: 0,
m21: mSin,
m22: mCos,
m23: 0,
m24: 0,
m31: 0,
m32: 0,
m33: 1,
m34: 0,
m41: 0,
m42: 0,
m43: 0,
m44: 1)
return CATransform3DConcat(transform3, CATransform3DConcat(transform2, transform1))
}
static func makeTransform(
anchor: CGPoint,
position: CGPoint,
scale: CGSize,
rotationX: CGFloat,
rotationY: CGFloat,
rotationZ: CGFloat,
skew: CGFloat?,
skewAxis: CGFloat?)
-> CATransform3D
{
if let skew, let skewAxis {
return CATransform3DMakeTranslation(position.x, position.y, 0)
.rotated(rotationX, axis: .x)
.rotated(rotationY, axis: .y)
.rotated(rotationZ, axis: .z)
.skewed(skew: -skew, skewAxis: skewAxis)
.scaled(scale * 0.01)
.translated(anchor * -1)
}
return CATransform3DMakeTranslation(position.x, position.y, 0)
.rotated(rotationX, axis: .x)
.rotated(rotationY, axis: .y)
.rotated(rotationZ, axis: .z)
.scaled(scale * 0.01)
.translated(anchor * -1)
}
func rotated(_ degrees: CGFloat, axis: Axis) -> CATransform3D {
CATransform3DRotate(
self,
degrees.toRadians(),
axis == .x ? 1 : 0,
axis == .y ? 1 : 0,
axis == .z ? 1 : 0)
}
func translated(_ translation: CGPoint) -> CATransform3D {
CATransform3DTranslate(self, translation.x, translation.y, 0)
}
func scaled(_ scale: CGSize) -> CATransform3D {
CATransform3DScale(self, scale.width, scale.height, 1)
}
func skewed(skew: CGFloat, skewAxis: CGFloat) -> CATransform3D {
CATransform3DConcat(CATransform3D.makeSkew(skew: skew, skewAxis: skewAxis), self)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/Utility/Primitives/VectorsExtensions.swift
|
Swift
|
unknown
| 7,646
|
//
// LottieAnimation.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/7/19.
//
import Foundation
// MARK: - CoordinateSpace
public enum CoordinateSpace: Int, Codable, Sendable {
case type2d
case type3d
}
// MARK: - LottieAnimation
/// The `LottieAnimation` model is the top level model object in Lottie.
///
/// A `LottieAnimation` holds all of the animation data backing a Lottie Animation.
/// Codable, see JSON schema [here](https://github.com/airbnb/lottie-web/tree/master/docs/json).
public final class LottieAnimation: Codable, Sendable, DictionaryInitializable {
// MARK: Lifecycle
required public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: LottieAnimation.CodingKeys.self)
version = try container.decode(String.self, forKey: .version)
type = try container.decodeIfPresent(CoordinateSpace.self, forKey: .type) ?? .type2d
startFrame = try container.decode(AnimationFrameTime.self, forKey: .startFrame)
endFrame = try container.decode(AnimationFrameTime.self, forKey: .endFrame)
framerate = try container.decode(Double.self, forKey: .framerate)
width = try container.decode(Double.self, forKey: .width)
height = try container.decode(Double.self, forKey: .height)
layers = try container.decode([LayerModel].self, ofFamily: LayerType.self, forKey: .layers)
glyphs = try container.decodeIfPresent([Glyph].self, forKey: .glyphs)
fonts = try container.decodeIfPresent(FontList.self, forKey: .fonts)
assetLibrary = try container.decodeIfPresent(AssetLibrary.self, forKey: .assetLibrary)
markers = try container.decodeIfPresent([Marker].self, forKey: .markers)
if let markers {
var markerMap: [String: Marker] = [:]
for marker in markers {
markerMap[marker.name] = marker
}
self.markerMap = markerMap
} else {
markerMap = nil
}
}
public init(dictionary: [String: Any]) throws {
version = try dictionary.value(for: CodingKeys.version)
if
let typeRawValue = dictionary[CodingKeys.type.rawValue] as? Int,
let type = CoordinateSpace(rawValue: typeRawValue)
{
self.type = type
} else {
type = .type2d
}
startFrame = try dictionary.value(for: CodingKeys.startFrame)
endFrame = try dictionary.value(for: CodingKeys.endFrame)
framerate = try dictionary.value(for: CodingKeys.framerate)
width = try dictionary.value(for: CodingKeys.width)
height = try dictionary.value(for: CodingKeys.height)
let layerDictionaries: [[String: Any]] = try dictionary.value(for: CodingKeys.layers)
layers = try [LayerModel].fromDictionaries(layerDictionaries)
if let glyphDictionaries = dictionary[CodingKeys.glyphs.rawValue] as? [[String: Any]] {
glyphs = try glyphDictionaries.map { try Glyph(dictionary: $0) }
} else {
glyphs = nil
}
if let fontsDictionary = dictionary[CodingKeys.fonts.rawValue] as? [String: Any] {
fonts = try FontList(dictionary: fontsDictionary)
} else {
fonts = nil
}
if let assetLibraryDictionaries = dictionary[CodingKeys.assetLibrary.rawValue] as? [[String: Any]] {
assetLibrary = try AssetLibrary(value: assetLibraryDictionaries)
} else {
assetLibrary = nil
}
if let markerDictionaries = dictionary[CodingKeys.markers.rawValue] as? [[String: Any]] {
let markers = try markerDictionaries.map { try Marker(dictionary: $0) }
var markerMap: [String: Marker] = [:]
for marker in markers {
markerMap[marker.name] = marker
}
self.markers = markers
self.markerMap = markerMap
} else {
markers = nil
markerMap = nil
}
}
// MARK: Public
/// The start time of the composition in frameTime.
public let startFrame: AnimationFrameTime
/// The end time of the composition in frameTime.
public let endFrame: AnimationFrameTime
/// The frame rate of the composition.
public let framerate: Double
/// Return all marker names, in order, or an empty list if none are specified
public var markerNames: [String] {
guard let markers else { return [] }
return markers.map { $0.name }
}
// MARK: Internal
enum CodingKeys: String, CodingKey {
case version = "v"
case type = "ddd"
case startFrame = "ip"
case endFrame = "op"
case framerate = "fr"
case width = "w"
case height = "h"
case layers
case glyphs = "chars"
case fonts
case assetLibrary = "assets"
case markers
}
/// The version of the JSON Schema.
let version: String
/// The coordinate space of the composition.
let type: CoordinateSpace
/// The height of the composition in points.
let width: Double
/// The width of the composition in points.
let height: Double
/// The list of animation layers
let layers: [LayerModel]
/// The list of glyphs used for text rendering
let glyphs: [Glyph]?
/// The list of fonts used for text rendering
let fonts: FontList?
/// Asset Library
let assetLibrary: AssetLibrary?
/// Markers
let markers: [Marker]?
let markerMap: [String: Marker]?
/// The marker to use if "reduced motion" is enabled.
/// Supported marker names are case insensitive, and include:
/// - reduced motion
/// - reducedMotion
/// - reduced_motion
/// - reduced-motion
var reducedMotionMarker: Marker? {
let allowedReducedMotionMarkerNames = Set([
"reduced motion",
"reduced_motion",
"reduced-motion",
"reducedmotion",
])
return markers?.first(where: { marker in
allowedReducedMotionMarkerNames.contains(marker.name.lowercased())
})
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Animation/LottieAnimation.swift
|
Swift
|
unknown
| 5,671
|
//
// AnimationPublic.swift
// lottie-swift
//
// Created by Brandon Withrow on 2/5/19.
//
import CoreGraphics
import Foundation
extension LottieAnimation {
/// A closure for an Animation download. The closure is passed `nil` if there was an error.
public typealias DownloadClosure = (LottieAnimation?) -> Void
/// The duration in seconds of the animation.
public var duration: TimeInterval {
Double(endFrame - startFrame) / framerate
}
/// The natural bounds in points of the animation.
public var bounds: CGRect {
CGRect(x: 0, y: 0, width: width, height: height)
}
/// The natural size in points of the animation.
public var size: CGSize {
CGSize(width: width, height: height)
}
// MARK: Animation (Loading)
/// Loads an animation model from a bundle by its name. Returns `nil` if an animation is not found.
///
/// - Parameter name: The name of the json file without the json extension. EG "StarAnimation"
/// - Parameter bundle: The bundle in which the animation is located. Defaults to `Bundle.main`
/// - Parameter subdirectory: A subdirectory in the bundle in which the animation is located. Optional.
/// - Parameter animationCache: A cache for holding loaded animations. Defaults to `LottieAnimationCache.shared`. Optional.
///
/// - Returns: Deserialized `LottieAnimation`. Optional.
public static func named(
_ name: String,
bundle: Bundle = Bundle.main,
subdirectory: String? = nil,
animationCache: AnimationCacheProvider? = LottieAnimationCache.shared)
-> LottieAnimation?
{
/// Create a cache key for the animation.
let cacheKey = bundle.bundlePath + (subdirectory ?? "") + "/" + name
/// Check cache for animation
if
let animationCache,
let animation = animationCache.animation(forKey: cacheKey)
{
/// If found, return the animation.
return animation
}
do {
/// Decode animation.
let json = try bundle.getAnimationData(name, subdirectory: subdirectory)
let animation = try LottieAnimation.from(data: json)
animationCache?.setAnimation(animation, forKey: cacheKey)
return animation
} catch {
/// Decoding error.
LottieLogger.shared.warn("Error when decoding animation \"\(name)\": \(error)")
return nil
}
}
/// Loads an animation from a specific filepath.
/// - Parameter filepath: The absolute filepath of the animation to load. EG "/User/Me/starAnimation.json"
/// - Parameter animationCache: A cache for holding loaded animations. Defaults to `LottieAnimationCache.shared`. Optional.
///
/// - Returns: Deserialized `LottieAnimation`. Optional.
public static func filepath(
_ filepath: String,
animationCache: AnimationCacheProvider? = LottieAnimationCache.shared)
-> LottieAnimation?
{
/// Check cache for animation
if
let animationCache,
let animation = animationCache.animation(forKey: filepath)
{
return animation
}
do {
/// Decode the animation.
let json = try Data(contentsOf: URL(fileURLWithPath: filepath))
let animation = try LottieAnimation.from(data: json)
animationCache?.setAnimation(animation, forKey: filepath)
return animation
} catch {
LottieLogger.shared.warn("""
Failed to load animation from filepath \(filepath)
with underlying error: \(error.localizedDescription)
""")
return nil
}
}
/// Loads an animation model from the asset catalog by its name. Returns `nil` if an animation is not found.
/// - Parameter name: The name of the json file in the asset catalog. EG "StarAnimation"
/// - Parameter bundle: The bundle in which the animation is located. Defaults to `Bundle.main`
/// - Parameter animationCache: A cache for holding loaded animations. Defaults to `LottieAnimationCache.shared` Optional.
/// - Returns: Deserialized `LottieAnimation`. Optional.
public static func asset(
_ name: String,
bundle: Bundle = Bundle.main,
animationCache: AnimationCacheProvider? = LottieAnimationCache.shared)
-> LottieAnimation?
{
/// Create a cache key for the animation.
let cacheKey = bundle.bundlePath + "/" + name
/// Check cache for animation
if
let animationCache,
let animation = animationCache.animation(forKey: cacheKey)
{
/// If found, return the animation.
return animation
}
do {
/// Load jsonData from Asset
let json = try Data(assetName: name, in: bundle)
/// Decode animation.
let animation = try LottieAnimation.from(data: json)
animationCache?.setAnimation(animation, forKey: cacheKey)
return animation
} catch {
LottieLogger.shared.warn("""
Failed to load animation with asset name \(name)
in \(bundle.bundlePath)
with underlying error: \(error.localizedDescription)
""")
return nil
}
}
/// Loads a Lottie animation from a `Data` object containing a JSON animation.
///
/// - Parameter data: The object to load the animation from.
/// - Parameter strategy: How the data should be decoded. Defaults to using the strategy set in `LottieConfiguration.shared`.
/// - Returns: Deserialized `LottieAnimation`. Optional.
///
public static func from(
data: Data,
strategy: DecodingStrategy = LottieConfiguration.shared.decodingStrategy)
throws -> LottieAnimation
{
switch strategy {
case .legacyCodable:
return try JSONDecoder().decode(LottieAnimation.self, from: data)
case .dictionaryBased:
let json = try JSONSerialization.jsonObject(with: data)
guard let dict = json as? [String: Any] else {
throw InitializableError.invalidInput()
}
return try LottieAnimation(dictionary: dict)
}
}
/// Loads a Lottie animation asynchronously from the URL.
///
/// - Parameter url: The url to load the animation from.
/// - Parameter animationCache: A cache for holding loaded animations. Defaults to `LottieAnimationCache.shared`. Optional.
///
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public static func loadedFrom(
url: URL,
session: URLSession = .shared,
animationCache: AnimationCacheProvider? = LottieAnimationCache.shared)
async -> LottieAnimation?
{
await withCheckedContinuation { continuation in
LottieAnimation.loadedFrom(
url: url,
session: session,
closure: { result in
continuation.resume(returning: result)
},
animationCache: animationCache)
}
}
/// Loads a Lottie animation asynchronously from the URL.
///
/// - Parameter url: The url to load the animation from.
/// - Parameter closure: A closure to be called when the animation has loaded.
/// - Parameter animationCache: A cache for holding loaded animations. Defaults to `LottieAnimationCache.shared`. Optional.
///
public static func loadedFrom(
url: URL,
session: URLSession = .shared,
closure: @escaping LottieAnimation.DownloadClosure,
animationCache: AnimationCacheProvider? = LottieAnimationCache.shared)
{
if let animationCache, let animation = animationCache.animation(forKey: url.absoluteString) {
closure(animation)
} else {
let task = session.dataTask(with: url) { data, _, error in
guard error == nil, let jsonData = data else {
DispatchQueue.main.async {
closure(nil)
}
return
}
do {
let animation = try LottieAnimation.from(data: jsonData)
DispatchQueue.main.async {
animationCache?.setAnimation(animation, forKey: url.absoluteString)
closure(animation)
}
} catch {
DispatchQueue.main.async {
closure(nil)
}
}
}
task.resume()
}
}
// MARK: Animation (Helpers)
/// Markers are a way to describe a point in time by a key name.
///
/// Markers are encoded into animation JSON. By using markers a designer can mark
/// playback points for a developer to use without having to worry about keeping
/// track of animation frames. If the animation file is updated, the developer
/// does not need to update playback code.
///
/// Returns the Progress Time for the marker named. Returns nil if no marker found.
public func progressTime(forMarker named: String) -> AnimationProgressTime? {
guard let markers = markerMap, let marker = markers[named] else {
return nil
}
return progressTime(forFrame: marker.frameTime)
}
/// Markers are a way to describe a point in time by a key name.
///
/// Markers are encoded into animation JSON. By using markers a designer can mark
/// playback points for a developer to use without having to worry about keeping
/// track of animation frames. If the animation file is updated, the developer
/// does not need to update playback code.
///
/// Returns the Frame Time for the marker named. Returns nil if no marker found.
public func frameTime(forMarker named: String) -> AnimationFrameTime? {
guard let markers = markerMap, let marker = markers[named] else {
return nil
}
return marker.frameTime
}
/// Markers are a way to describe a point in time and a duration by a key name.
///
/// Markers are encoded into animation JSON. By using markers a designer can mark
/// playback points for a developer to use without having to worry about keeping
/// track of animation frames. If the animation file is updated, the developer
/// does not need to update playback code.
///
/// - Returns: The duration frame time for the marker, or `nil` if no marker found.
public func durationFrameTime(forMarker named: String) -> AnimationFrameTime? {
guard let marker = markerMap?[named] else {
return nil
}
return marker.durationFrameTime
}
/// Converts Frame Time (Seconds * Framerate) into Progress Time
/// (optionally clamped to between 0 and 1).
public func progressTime(
forFrame frameTime: AnimationFrameTime,
clamped: Bool = true)
-> AnimationProgressTime
{
let progressTime = ((frameTime - startFrame) / (endFrame - startFrame))
if clamped {
return progressTime.clamp(0, 1)
} else {
return progressTime
}
}
/// Converts Progress Time (0 to 1) into Frame Time (Seconds * Framerate)
public func frameTime(forProgress progressTime: AnimationProgressTime) -> AnimationFrameTime {
((endFrame - startFrame) * progressTime) + startFrame
}
/// Converts Frame Time (Seconds * Framerate) into Time (Seconds)
public func time(forFrame frameTime: AnimationFrameTime) -> TimeInterval {
Double(frameTime - startFrame) / framerate
}
/// Converts Time (Seconds) into Frame Time (Seconds * Framerate)
public func frameTime(forTime time: TimeInterval) -> AnimationFrameTime {
CGFloat(time * framerate) + startFrame
}
}
// MARK: - Foundation.Bundle + Sendable
/// Necessary to suppress warnings like:
/// ```
/// Non-sendable type 'Bundle' exiting main actor-isolated context in call to non-isolated
/// static method 'named(_:bundle:subdirectory:dotLottieCache:)' cannot cross actor boundary
/// ```
/// This retroactive conformance is safe because Sendable is a marker protocol that doesn't
/// include any runtime component. Multiple modules in the same package graph can provide this
/// conformance without causing any conflicts.
///
// swiftlint:disable:next no_unchecked_sendable
extension Foundation.Bundle: @unchecked Sendable { }
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Animation/LottieAnimationHelpers.swift
|
Swift
|
unknown
| 11,624
|
//
// LottieAnimationLayer.swift
// Lottie
//
import QuartzCore
// MARK: - LottieAnimationLayer
/// A CALayer subclass for rendering Lottie animations.
/// - Also available as a SwiftUI view (`LottieView`) and a UIView subclass (`LottieAnimationView`)
public class LottieAnimationLayer: CALayer {
// MARK: Lifecycle
/// Initializes a LottieAnimationLayer with an animation.
public init(
animation: LottieAnimation?,
imageProvider: AnimationImageProvider? = nil,
textProvider: AnimationKeypathTextProvider = DefaultTextProvider(),
fontProvider: AnimationFontProvider = DefaultFontProvider(),
configuration: LottieConfiguration = .shared,
logger: LottieLogger = .shared)
{
self.animation = animation
self.imageProvider = imageProvider ?? BundleImageProvider(bundle: Bundle.main, searchPath: nil)
self.textProvider = textProvider
self.fontProvider = fontProvider
self.configuration = configuration
screenScale = 1
self.logger = logger
super.init()
makeAnimationLayer(usingEngine: configuration.renderingEngine)
if let animation {
frame = animation.bounds
}
}
/// Initializes an LottieAnimationLayer with a .lottie file.
public init(
dotLottie: DotLottieFile?,
animationId: String? = nil,
textProvider: AnimationKeypathTextProvider = DefaultTextProvider(),
fontProvider: AnimationFontProvider = DefaultFontProvider(),
configuration: LottieConfiguration = .shared,
logger: LottieLogger = .shared)
{
let dotLottieAnimation = dotLottie?.animation(for: animationId)
animation = dotLottieAnimation?.animation
imageProvider = dotLottie?.imageProvider ?? BundleImageProvider(bundle: Bundle.main, searchPath: nil)
self.textProvider = textProvider
self.fontProvider = fontProvider
self.configuration = configuration
screenScale = 1
self.logger = logger
super.init()
loopMode = dotLottieAnimation?.configuration.loopMode ?? .playOnce
animationSpeed = CGFloat(dotLottieAnimation?.configuration.speed ?? 1)
makeAnimationLayer(usingEngine: configuration.renderingEngine)
if let animation {
frame = animation.bounds
}
}
public init(
configuration: LottieConfiguration = .shared,
logger: LottieLogger = .shared)
{
animation = nil
imageProvider = BundleImageProvider(bundle: Bundle.main, searchPath: nil)
textProvider = DefaultTextProvider()
fontProvider = DefaultFontProvider()
self.configuration = configuration
screenScale = 1
self.logger = logger
super.init()
}
/// Called by CoreAnimation to create a shadow copy of this layer
/// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
override init(layer: Any) {
guard let typedLayer = layer as? Self else {
fatalError("\(Self.self).init(layer:) incorrectly called with \(type(of: layer))")
}
animation = typedLayer.animation
imageProvider = typedLayer.imageProvider
textProvider = typedLayer.textProvider
fontProvider = typedLayer.fontProvider
logger = typedLayer.logger
screenScale = typedLayer.screenScale
configuration = typedLayer.configuration
super.init(layer: typedLayer)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Open
/// Plays the animation from its current state to the end.
///
/// - Parameter completion: An optional completion closure to be called when the animation completes playing.
open func play(completion: LottieCompletionBlock? = nil) {
guard let animation else { return }
defer {
currentPlaybackMode = .playing(.fromProgress(nil, toProgress: 1, loopMode: loopMode))
}
if shouldOverrideWithReducedMotionAnimation {
playReducedMotionAnimation(completion: completion)
return
}
/// Build a context for the animation.
let context = AnimationContext(
playFrom: CGFloat(animation.startFrame),
playTo: CGFloat(animation.endFrame),
closure: completion)
removeCurrentAnimationIfNecessary()
addNewAnimationForContext(context)
}
/// Plays the animation from a progress (0-1) to a progress (0-1).
///
/// - Parameter fromProgress: The start progress of the animation. If `nil` the animation will start at the current progress.
/// - Parameter toProgress: The end progress of the animation.
/// - Parameter loopMode: The loop behavior of the animation. If `nil` the layer's `loopMode` property will be used.
/// - Parameter completion: An optional completion closure to be called when the animation stops.
open func play(
fromProgress: AnimationProgressTime? = nil,
toProgress: AnimationProgressTime,
loopMode: LottieLoopMode? = nil,
completion: LottieCompletionBlock? = nil)
{
guard let animation else { return }
defer {
currentPlaybackMode = .playing(.fromProgress(fromProgress, toProgress: toProgress, loopMode: loopMode ?? self.loopMode))
}
if shouldOverrideWithReducedMotionAnimation {
playReducedMotionAnimation(completion: completion)
return
}
removeCurrentAnimationIfNecessary()
if let loopMode {
/// Set the loop mode, if one was supplied
self.loopMode = loopMode
}
let context = AnimationContext(
playFrom: animation.frameTime(forProgress: fromProgress ?? currentProgress),
playTo: animation.frameTime(forProgress: toProgress),
closure: completion)
addNewAnimationForContext(context)
}
/// Plays the animation from a start frame to an end frame in the animation's framerate.
///
/// - Parameter fromFrame: The start frame of the animation. If `nil` the animation will start at the current frame.
/// - Parameter toFrame: The end frame of the animation.
/// - Parameter loopMode: The loop behavior of the animation. If `nil` the layer's `loopMode` property will be used.
/// - Parameter completion: An optional completion closure to be called when the animation stops.
open func play(
fromFrame: AnimationFrameTime? = nil,
toFrame: AnimationFrameTime,
loopMode: LottieLoopMode? = nil,
completion: LottieCompletionBlock? = nil)
{
defer {
currentPlaybackMode = .playing(.fromFrame(fromFrame, toFrame: toFrame, loopMode: loopMode ?? self.loopMode))
}
if shouldOverrideWithReducedMotionAnimation {
playReducedMotionAnimation(completion: completion)
return
}
removeCurrentAnimationIfNecessary()
if let loopMode {
/// Set the loop mode, if one was supplied
self.loopMode = loopMode
}
let context = AnimationContext(
playFrom: fromFrame ?? currentFrame,
playTo: toFrame,
closure: completion)
addNewAnimationForContext(context)
}
/// Plays the animation from a named marker to another marker.
///
/// Markers are point in time that are encoded into the Animation data and assigned
/// a name.
///
/// NOTE: If markers are not found the play command will exit.
///
/// - Parameter fromMarker: The start marker for the animation playback. If `nil` the
/// animation will start at the current progress.
/// - Parameter toMarker: The end marker for the animation playback.
/// - Parameter playEndMarkerFrame: A flag to determine whether or not to play the frame of the end marker. If the
/// end marker represents the end of the section to play, it should be to true. If the provided end marker
/// represents the beginning of the next section, it should be false.
/// - Parameter loopMode: The loop behavior of the animation. If `nil` the layer's `loopMode` property will be used.
/// - Parameter completion: An optional completion closure to be called when the animation stops.
open func play(
fromMarker: String? = nil,
toMarker: String,
playEndMarkerFrame: Bool = true,
loopMode: LottieLoopMode? = nil,
completion: LottieCompletionBlock? = nil)
{
defer {
currentPlaybackMode = .playing(.fromMarker(
fromMarker,
toMarker: toMarker,
playEndMarkerFrame: playEndMarkerFrame,
loopMode: loopMode ?? self.loopMode))
}
if shouldOverrideWithReducedMotionAnimation {
playReducedMotionAnimation(completion: completion)
return
}
guard let animation, let markers = animation.markerMap, let to = markers[toMarker] else {
return
}
removeCurrentAnimationIfNecessary()
if let loopMode {
/// Set the loop mode, if one was supplied
self.loopMode = loopMode
}
let fromTime: CGFloat
if let fromName = fromMarker, let from = markers[fromName] {
fromTime = CGFloat(from.frameTime)
} else {
fromTime = currentFrame
}
let playTo = playEndMarkerFrame ? CGFloat(to.frameTime) : CGFloat(to.frameTime) - 1
let context = AnimationContext(
playFrom: fromTime,
playTo: playTo,
closure: completion)
addNewAnimationForContext(context)
}
/// Plays the animation from a named marker to the end of the marker's duration.
///
/// A marker is a point in time with an associated duration that is encoded into the
/// animation data and assigned a name.
///
/// NOTE: If marker is not found the play command will exit.
///
/// - Parameter marker: The start marker for the animation playback.
/// - Parameter loopMode: The loop behavior of the animation. If `nil` the layer's `loopMode` property will be used.
/// - Parameter completion: An optional completion closure to be called when the animation stops.
open func play(
marker: String,
loopMode: LottieLoopMode? = nil,
completion: LottieCompletionBlock? = nil)
{
guard let from = animation?.markerMap?[marker] else {
return
}
defer {
currentPlaybackMode = .playing(.marker(marker, loopMode: loopMode ?? self.loopMode))
}
if shouldOverrideWithReducedMotionAnimation {
playReducedMotionAnimation(completion: completion)
return
}
play(
fromFrame: from.frameTime,
toFrame: from.frameTime + from.durationFrameTime,
loopMode: loopMode,
completion: completion)
}
/// Plays the given markers sequentially in order.
///
/// A marker is a point in time with an associated duration that is encoded into the
/// animation data and assigned a name. Multiple markers can be played sequentially
/// to create programmable animations.
///
/// If a marker is not found, it will be skipped.
///
/// If a marker doesn't have a duration value, it will play with a duration of 0
/// (effectively being skipped).
///
/// If another animation is played (by calling any `play` method) while this
/// marker sequence is playing, the marker sequence will be cancelled.
///
/// - Parameter markers: The list of markers to play sequentially.
/// - Parameter completion: An optional completion closure to be called when the animation stops.
open func play(
markers: [String],
completion: LottieCompletionBlock? = nil)
{
guard !markers.isEmpty else { return }
defer {
currentPlaybackMode = .playing(.markers(markers))
}
if shouldOverrideWithReducedMotionAnimation {
playReducedMotionAnimation(completion: nil)
return
}
let markerToPlay = markers[0]
let followingMarkers = Array(markers.dropFirst())
guard animation?.markerMap?[markerToPlay] != nil else {
play(markers: followingMarkers, completion: completion)
return
}
play(marker: markerToPlay, loopMode: .playOnce, completion: { [weak self] completed in
// If the completion handler is called with `completed: false` (which typically means
// that another animation was played by calling some `play` method),
// we should cancel the marker sequence and not play the next marker.
guard completed, let self else {
completion?(false)
return
}
if followingMarkers.isEmpty {
// If we don't have any more markers to play, then the marker sequence has completed.
completion?(completed)
} else {
self.play(markers: followingMarkers, completion: completion)
}
})
}
/// Stops the animation and resets the layer to its start frame.
///
/// The completion closure will be called with `false`
open func stop() {
removeCurrentAnimation()
currentFrame = 0
}
/// Pauses the animation in its current state.
///
/// The completion closure will be called with `false`
open func pause() {
pause(at: .currentFrame)
}
/// Pauses the animation at a given state.
open func pause(at state: LottiePlaybackMode.PausedState) {
switch state {
case .currentFrame:
removeCurrentAnimation()
case .progress(let animationProgressTime):
currentProgress = animationProgressTime
case .frame(let animationFrameTime):
currentFrame = animationFrameTime
case .time(let timeInterval):
currentTime = timeInterval
case .marker(let name, let position):
guard let from = animation?.markerMap?[name] else {
return
}
switch position {
case .start:
currentTime = from.frameTime
case .end:
currentTime = from.frameTime + from.durationFrameTime
}
}
currentPlaybackMode = .paused(at: state)
}
@available(*, deprecated, renamed: "setPlaybackMode(_:completion:)", message: "Will be removed in a future major release.")
open func play(
_ playbackMode: LottiePlaybackMode,
animationCompletionHandler: LottieCompletionBlock? = nil)
{
setPlaybackMode(playbackMode, completion: animationCompletionHandler)
}
/// Applies the given `LottiePlaybackMode` to this layer.
/// - Parameter playbackMode: The playback mode to apply
/// - Parameter completion: A closure that is called after
/// an animation triggered by this method completes.
open func setPlaybackMode(
_ playbackMode: LottiePlaybackMode,
completion: LottieCompletionBlock? = nil)
{
switch playbackMode {
case .paused(at: let state):
pause(at: state)
case .playing(let mode):
play(mode, completion: completion)
case .progress(let progress):
pause(at: .progress(progress))
case .frame(let frame):
pause(at: .frame(frame))
case .time(let time):
pause(at: .time(time))
case .pause:
pause(at: .currentFrame)
case .fromProgress(let from, let to, let loopMode):
play(.fromProgress(from, toProgress: to, loopMode: loopMode), completion: completion)
case .fromFrame(let from, let to, let loopMode):
play(.fromFrame(from, toFrame: to, loopMode: loopMode), completion: completion)
case .fromMarker(let from, let to, let playEndMarkerFrame, let loopMode):
play(.fromMarker(from, toMarker: to, playEndMarkerFrame: playEndMarkerFrame, loopMode: loopMode), completion: completion)
case .marker(let name, let loopMode):
play(.marker(name, loopMode: loopMode), completion: completion)
case .markers(let names):
play(.markers(names), completion: completion)
}
}
/// Applies the given `LottiePlaybackMode` to this layer.
/// - Parameter playbackMode: The playback mode to apply
/// - Parameter completion: A closure that is called after
/// an animation triggered by this method completes.
open func play(_ playbackMode: LottiePlaybackMode.PlaybackMode, completion: LottieCompletionBlock? = nil) {
switch playbackMode {
case .fromProgress(let from, let to, let loopMode):
play(
fromProgress: from,
toProgress: to,
loopMode: loopMode,
completion: completion)
case .fromFrame(let from, let to, let loopMode):
play(
fromFrame: from,
toFrame: to,
loopMode: loopMode,
completion: completion)
case .fromMarker(let from, let to, let playEndMarkerFrame, let loopMode):
play(
fromMarker: from,
toMarker: to,
playEndMarkerFrame: playEndMarkerFrame,
loopMode: loopMode,
completion: completion)
case .marker(let name, loopMode: let loopMode):
play(marker: name, loopMode: loopMode, completion: completion)
case .markers(let names):
play(markers: names, completion: completion)
}
}
// MARK: Public
/// The current `LottiePlaybackMode` that is being used
public private(set) var currentPlaybackMode: LottiePlaybackMode?
/// Value Providers that have been registered using `setValueProvider(_:keypath:)`
public private(set) var valueProviders = [AnimationKeypath: AnyValueProvider]()
/// A closure called when the animation layer has been loaded.
/// Will inform the receiver the type of rendering engine that is used for the layer.
public var animationLayerDidLoad: ((_ animationLayer: LottieAnimationLayer, _ renderingEngine: RenderingEngineOption) -> Void)?
/// The configuration that this `LottieAnimationView` uses when playing its animation
public var configuration: LottieConfiguration {
didSet {
if configuration.renderingEngine != oldValue.renderingEngine {
makeAnimationLayer(usingEngine: configuration.renderingEngine)
}
}
}
/// The underlying CALayer created to display the content.
/// Use this property to change CALayer props like the content's transform, anchor point, etc.
public var animationLayer: CALayer? { rootAnimationLayer }
public var screenScale: CGFloat {
didSet {
rootAnimationLayer?.renderScale = screenScale
}
}
/// Describes the behavior of an AnimationView when the app is moved to the background.
///
/// The default for the Main Thread animation engine is `pause`,
/// which pauses the animation when the application moves to
/// the background. This prevents the animation from consuming CPU
/// resources when not on-screen. The completion block is called with
/// `false` for completed.
///
/// The default for the Core Animation engine is `continuePlaying`,
/// since the Core Animation engine does not have any CPU overhead.
public var backgroundBehavior: LottieBackgroundBehavior {
get {
let currentBackgroundBehavior = _backgroundBehavior ?? .default(for: currentRenderingEngine ?? .mainThread)
if
currentRenderingEngine == .mainThread,
_backgroundBehavior == .continuePlaying
{
logger.assertionFailure("""
`LottieBackgroundBehavior.continuePlaying` should not be used with the Main Thread
rendering engine, since this would waste CPU resources on playing an animation
that is not visible. Consider using a different background mode, or switching to
the Core Animation rendering engine (which does not have any CPU overhead).
""")
}
return currentBackgroundBehavior
}
set {
_backgroundBehavior = newValue
}
}
/// Sets the animation backing the animation layer. Setting this will clear the
/// layer's contents, completion blocks and current state. The new animation will
/// be loaded up and set to the beginning of its timeline.
public var animation: LottieAnimation? {
didSet {
makeAnimationLayer(usingEngine: configuration.renderingEngine)
if let animation {
animationLoaded?(self, animation)
}
}
}
/// A closure that is called when `self.animation` is loaded. When setting this closure,
/// it is called immediately if `self.animation` is non-nil.
///
/// When initializing a `LottieAnimationView`, the animation will either be loaded
/// synchronously (when loading a `LottieAnimation` from a .json file on disk)
/// or asynchronously (when loading a `DotLottieFile` from disk, or downloading
/// an animation from a URL). This closure is called in both cases once the
/// animation is loaded and applied, so can be a useful way to configure this
/// `LottieAnimationView` regardless of which initializer was used. For example:
///
/// ```
/// let animationView: LottieAnimationView
///
/// if loadDotLottieFile {
/// // Loads the .lottie file asynchronously
/// animationView = LottieAnimationView(dotLottieName: "animation")
/// } else {
/// // Loads the .json file synchronously
/// animationView = LottieAnimationView(name: "animation")
/// }
///
/// animationView.animationLoaded = { animationView, animation in
/// // If using a .lottie file, this is called once the file finishes loading.
/// // If using a .json file, this is called immediately (since the animation is loaded synchronously).
/// animationView.play()
/// }
/// ```
public var animationLoaded: ((_ animationLayer: LottieAnimationLayer, _ animation: LottieAnimation) -> Void)? {
didSet {
if let animation {
animationLoaded?(self, animation)
}
}
}
/// Sets the image provider for the animation layer. An image provider provides the
/// animation with its required image data.
///
/// Setting this will cause the animation to reload its image contents.
public var imageProvider: AnimationImageProvider {
didSet {
rootAnimationLayer?.imageProvider = imageProvider.cachedImageProvider
reloadImages()
}
}
/// Sets the text provider for animation layer. A text provider provides the
/// animation with values for text layers
public var textProvider: AnimationKeypathTextProvider {
didSet {
rootAnimationLayer?.textProvider = textProvider
}
}
/// Sets the text provider for animation layer. A text provider provides the
/// animation with values for text layers
public var fontProvider: AnimationFontProvider {
didSet {
rootAnimationLayer?.fontProvider = fontProvider
}
}
/// Whether or not the animation is masked to the bounds. Defaults to true.
public var maskAnimationToBounds = true {
didSet {
animationLayer?.masksToBounds = maskAnimationToBounds
}
}
/// Returns `true` if the animation is currently playing.
public var isAnimationPlaying: Bool {
guard let animationLayer = rootAnimationLayer else {
return false
}
if let valueFromLayer = animationLayer.isAnimationPlaying {
return valueFromLayer
} else {
return animationLayer.animation(forKey: activeAnimationName) != nil
}
}
/// Sets the loop behavior for `play` calls. Defaults to `playOnce`
public var loopMode: LottieLoopMode = .playOnce {
didSet {
updateInFlightAnimation()
}
}
/// When `true` the animation layer will rasterize its contents when not animating.
/// Rasterizing will improve performance of static animations.
///
/// Note: this will not produce crisp results at resolutions above the animations natural resolution.
///
/// Defaults to `false`
public var shouldRasterizeWhenIdle = false {
didSet {
updateRasterizationState()
}
}
/// Sets the current animation time with a Progress Time
///
/// Note: Setting this will stop the current animation, if any.
/// Note 2: If `animation` is nil, setting this will fallback to 0
public var currentProgress: AnimationProgressTime {
set {
if let animation {
currentFrame = animation.frameTime(forProgress: newValue)
currentPlaybackMode = .paused(at: .progress(newValue))
} else {
currentFrame = 0
}
}
get {
if let animation {
return animation.progressTime(forFrame: currentFrame)
} else {
return 0
}
}
}
/// Sets the current animation time with a time in seconds.
///
/// Note: Setting this will stop the current animation, if any.
/// Note 2: If `animation` is nil, setting this will fallback to 0
public var currentTime: TimeInterval {
set {
if let animation {
currentFrame = animation.frameTime(forTime: newValue)
currentPlaybackMode = .paused(at: .time(newValue))
} else {
currentFrame = 0
}
}
get {
if let animation {
return animation.time(forFrame: currentFrame)
} else {
return 0
}
}
}
/// Sets the current animation time with a frame in the animations framerate.
///
/// Note: Setting this will stop the current animation, if any.
public var currentFrame: AnimationFrameTime {
set {
removeCurrentAnimationIfNecessary()
updateAnimationFrame(newValue)
currentPlaybackMode = .paused(at: .frame(currentFrame))
}
get {
rootAnimationLayer?.currentFrame ?? 0
}
}
/// Returns the current animation frame while an animation is playing.
public var realtimeAnimationFrame: AnimationFrameTime {
isAnimationPlaying ? rootAnimationLayer?.presentation()?.currentFrame ?? currentFrame : currentFrame
}
/// Returns the current animation frame while an animation is playing.
public var realtimeAnimationProgress: AnimationProgressTime {
if let animation {
return animation.progressTime(forFrame: realtimeAnimationFrame)
}
return 0
}
/// Sets the speed of the animation playback. Defaults to 1
public var animationSpeed: CGFloat = 1 {
didSet {
updateInFlightAnimation()
}
}
/// When `true` the animation will play back at the framerate encoded in the
/// `LottieAnimation` model. When `false` the animation will play at the framerate
/// of the device.
///
/// Defaults to false
public var respectAnimationFrameRate = false {
didSet {
rootAnimationLayer?.respectAnimationFrameRate = respectAnimationFrameRate
}
}
/// The rendering engine currently being used by this layer.
/// - This will only be `nil` in cases where the configuration is `automatic`
/// but a `RootAnimationLayer` hasn't been constructed yet
public var currentRenderingEngine: RenderingEngine? {
switch configuration.renderingEngine {
case .specific(let engine):
return engine
case .automatic:
guard let animationLayer else {
return nil
}
if animationLayer is CoreAnimationLayer {
return .coreAnimation
} else {
return .mainThread
}
}
}
/// Whether or not the Main Thread rendering engine should use `forceDisplayUpdate()`
/// when rendering each individual frame.
/// - The main thread rendering engine implements optimizations to decrease the amount
/// of properties that have to be re-rendered on each frame. There are some cases
/// where this can result in bugs / incorrect behavior, so we allow it to be disabled.
/// - Forcing a full render on every frame will decrease performance, and is not recommended
/// except as a workaround to a bug in the main thread rendering engine.
/// - Has no effect when using the Core Animation rendering engine.
public var mainThreadRenderingEngineShouldForceDisplayUpdateOnEachFrame = false {
didSet {
(rootAnimationLayer as? MainThreadAnimationLayer)?.forceDisplayUpdateOnEachFrame
= mainThreadRenderingEngineShouldForceDisplayUpdateOnEachFrame
}
}
/// Sets the lottie file backing the animation layer. Setting this will clear the
/// layer's contents, completion blocks and current state. The new animation will
/// be loaded up and set to the beginning of its timeline.
/// The loopMode, animationSpeed and imageProvider will be set according
/// to lottie file settings
/// - Parameters:
/// - animationId: Internal animation id to play. Optional
/// Defaults to play first animation in file.
/// - dotLottieFile: Lottie file to play
public func loadAnimation(
_ animationId: String? = nil,
from dotLottieFile: DotLottieFile)
{
guard let dotLottieAnimation = dotLottieFile.animation(for: animationId) else { return }
loadAnimation(dotLottieAnimation)
}
/// Sets the lottie file backing the animation layer. Setting this will clear the
/// layer's contents, completion blocks and current state. The new animation will
/// be loaded up and set to the beginning of its timeline.
/// The loopMode, animationSpeed and imageProvider will be set according
/// to lottie file settings
/// - Parameters:
/// - atIndex: Internal animation index to play.
/// Defaults to play first animation in file.
/// - dotLottieFile: Lottie file to play
public func loadAnimation(
atIndex index: Int,
from dotLottieFile: DotLottieFile)
{
guard let dotLottieAnimation = dotLottieFile.animation(at: index) else { return }
loadAnimation(dotLottieAnimation)
}
/// Reloads the images supplied to the animation from the `imageProvider`
public func reloadImages() {
rootAnimationLayer?.reloadImages()
}
/// Forces the LottieAnimationView to redraw its contents.
public func forceDisplayUpdate() {
rootAnimationLayer?.forceDisplayUpdate()
}
/// Sets a ValueProvider for the specified keypath. The value provider will be set
/// on all properties that match the keypath.
///
/// Nearly all properties of a Lottie animation can be changed at runtime using a
/// combination of `Animation Keypaths` and `Value Providers`.
/// Setting a ValueProvider on a keypath will cause the animation to update its
/// contents and read the new Value Provider.
///
/// A value provider provides a typed value on a frame by frame basis.
///
/// - Parameter valueProvider: The new value provider for the properties.
/// - Parameter keypath: The keypath used to search for properties.
///
/// Example:
/// ```
/// /// A keypath that finds the color value for all `Fill 1` nodes.
/// let fillKeypath = AnimationKeypath(keypath: "**.Fill 1.Color")
/// /// A Color Value provider that returns a reddish color.
/// let redValueProvider = ColorValueProvider(Color(r: 1, g: 0.2, b: 0.3, a: 1))
/// /// Set the provider on the animationView.
/// animationView.setValueProvider(redValueProvider, keypath: fillKeypath)
/// ```
public func setValueProvider(_ valueProvider: AnyValueProvider, keypath: AnimationKeypath) {
guard let animationLayer = rootAnimationLayer else { return }
valueProviders[keypath] = valueProvider
animationLayer.setValueProvider(valueProvider, keypath: keypath)
}
/// Reads the value of a property specified by the Keypath.
/// Returns nil if no property is found.
///
/// - Parameter for: The keypath used to search for the property.
/// - Parameter atFrame: The Frame Time of the value to query. If nil then the current frame is used.
public func getValue(for keypath: AnimationKeypath, atFrame: AnimationFrameTime?) -> Any? {
rootAnimationLayer?.getValue(for: keypath, atFrame: atFrame)
}
/// Reads the original value of a property specified by the Keypath.
/// This will ignore any value providers and can be useful when implementing a value providers that makes change to the original value from the animation.
/// Returns nil if no property is found.
///
/// - Parameter for: The keypath used to search for the property.
/// - Parameter atFrame: The Frame Time of the value to query. If nil then the current frame is used.
public func getOriginalValue(for keypath: AnimationKeypath, atFrame: AnimationFrameTime?) -> Any? {
rootAnimationLayer?.getOriginalValue(for: keypath, atFrame: atFrame)
}
/// Logs all child keypaths.
public func logHierarchyKeypaths() {
rootAnimationLayer?.logHierarchyKeypaths()
}
/// Computes and returns a list of all child keypaths in the current animation.
/// The returned list is the same as the log output of `logHierarchyKeypaths()`
public func allHierarchyKeypaths() -> [String] {
rootAnimationLayer?.allHierarchyKeypaths() ?? []
}
/// Converts a CGRect from the LottieAnimationView's coordinate space into the
/// coordinate space of the layer found at Keypath.
///
/// If no layer is found, nil is returned
///
/// - Parameter rect: The CGRect to convert.
/// - Parameter toLayerAt: The keypath used to find the layer.
public func convert(_ rect: CGRect, toLayerAt keypath: AnimationKeypath?) -> CGRect? {
guard let animationLayer = rootAnimationLayer else { return nil }
guard let keypath else {
return convert(rect, to: animationLayer)
}
guard let sublayer = animationLayer.layer(for: keypath) else {
return nil
}
setNeedsLayout()
layoutIfNeeded()
forceDisplayUpdate()
return animationLayer.convert(rect, to: sublayer)
}
/// Converts a CGPoint from the LottieAnimationView's coordinate space into the
/// coordinate space of the layer found at Keypath.
///
/// If no layer is found, nil is returned
///
/// - Parameter point: The CGPoint to convert.
/// - Parameter toLayerAt: The keypath used to find the layer.
public func convert(_ point: CGPoint, toLayerAt keypath: AnimationKeypath?) -> CGPoint? {
guard let animationLayer = rootAnimationLayer else { return nil }
guard let keypath else {
return convert(point, to: animationLayer)
}
guard let sublayer = animationLayer.layer(for: keypath) else {
return nil
}
setNeedsLayout()
layoutIfNeeded()
forceDisplayUpdate()
return animationLayer.convert(point, to: sublayer)
}
/// Sets the enabled state of all animator nodes found with the keypath search.
/// This can be used to interactively enable / disable parts of the animation.
///
/// - Parameter isEnabled: When true the animator nodes affect the rendering tree. When false the node is removed from the tree.
/// - Parameter keypath: The keypath used to find the node(s).
public func setNodeIsEnabled(isEnabled: Bool, keypath: AnimationKeypath) {
guard let animationLayer = rootAnimationLayer else { return }
let nodes = animationLayer.animatorNodes(for: keypath)
if let nodes {
for node in nodes {
node.isEnabled = isEnabled
}
forceDisplayUpdate()
}
}
/// Markers are a way to describe a point in time by a key name.
///
/// Markers are encoded into animation JSON. By using markers a designer can mark
/// playback points for a developer to use without having to worry about keeping
/// track of animation frames. If the animation file is updated, the developer
/// does not need to update playback code.
///
/// Returns the Progress Time for the marker named. Returns nil if no marker found.
public func progressTime(forMarker named: String) -> AnimationProgressTime? {
guard let animation else {
return nil
}
return animation.progressTime(forMarker: named)
}
/// Markers are a way to describe a point in time by a key name.
///
/// Markers are encoded into animation JSON. By using markers a designer can mark
/// playback points for a developer to use without having to worry about keeping
/// track of animation frames. If the animation file is updated, the developer
/// does not need to update playback code.
///
/// Returns the Frame Time for the marker named. Returns nil if no marker found.
public func frameTime(forMarker named: String) -> AnimationFrameTime? {
guard let animation else {
return nil
}
return animation.frameTime(forMarker: named)
}
/// Markers are a way to describe a point in time and a duration by a key name.
///
/// Markers are encoded into animation JSON. By using markers a designer can mark
/// playback points for a developer to use without having to worry about keeping
/// track of animation frames. If the animation file is updated, the developer
/// does not need to update playback code.
///
/// - Returns: The duration frame time for the marker, or `nil` if no marker found.
public func durationFrameTime(forMarker named: String) -> AnimationFrameTime? {
guard let animation else {
return nil
}
return animation.durationFrameTime(forMarker: named)
}
public func updateAnimationForBackgroundState() {
if let currentContext = animationContext {
switch backgroundBehavior {
case .stop:
removeCurrentAnimation()
updateAnimationFrame(currentContext.playFrom)
case .pause:
removeCurrentAnimation()
case .pauseAndRestore:
currentContext.closure.ignoreDelegate = true
removeCurrentAnimation()
/// Keep the stale context around for when the app enters the foreground.
animationContext = currentContext
case .forceFinish:
removeCurrentAnimation()
updateAnimationFrame(currentContext.playTo)
case .continuePlaying:
break
}
}
}
public func updateAnimationForForegroundState(wasWaitingToPlayAnimation: Bool) {
if let currentContext = animationContext {
if wasWaitingToPlayAnimation {
addNewAnimationForContext(currentContext)
} else if backgroundBehavior == .pauseAndRestore {
/// Restore animation from saved state
updateInFlightAnimation()
}
}
}
// MARK: Internal
var rootAnimationLayer: RootAnimationLayer? = nil
/// Context describing the animation that is currently playing in this `LottieAnimationView`
/// - When non-nil, an animation is currently playing in this layer. Otherwise,
/// the layer is paused on a specific frame.
fileprivate(set) var animationContext: AnimationContext?
var hasAnimationContext: Bool {
animationContext != nil
}
/// Set animation name from Interface Builder
var animationName: String? {
didSet {
animation = animationName.flatMap {
LottieAnimation.named($0, animationCache: nil)
}
}
}
/// Updates the animation frame. Does not affect any current animations
func updateAnimationFrame(_ newFrame: CGFloat) {
// In performance tests, we have to wrap the animation layer setup
// in a `CATransaction` in order for the layers to be deallocated at
// the correct time. The `CATransaction`s in this method interfere
// with the ones managed by the performance test, and aren't actually
// necessary in a headless environment, so we disable them.
if TestHelpers.performanceTestsAreRunning {
rootAnimationLayer?.currentFrame = newFrame
rootAnimationLayer?.forceDisplayUpdate()
return
}
CATransaction.begin()
CATransaction.setCompletionBlock {
self.rootAnimationLayer?.forceDisplayUpdate()
}
CATransaction.setDisableActions(true)
rootAnimationLayer?.currentFrame = newFrame
CATransaction.commit()
}
/// Updates an in flight animation.
func updateInFlightAnimation() {
guard let animationContext else { return }
guard animationContext.closure.animationState != .complete else {
// Tried to re-add an already completed animation. Cancel.
self.animationContext = nil
return
}
/// Tell existing context to ignore its closure
animationContext.closure.ignoreDelegate = true
/// Make a new context, stealing the completion block from the previous.
let newContext = AnimationContext(
playFrom: animationContext.playFrom,
playTo: animationContext.playTo,
closure: animationContext.closure.completionBlock)
/// Remove current animation, and freeze the current frame.
let pauseFrame = realtimeAnimationFrame
rootAnimationLayer?.removeAnimation(forKey: activeAnimationName)
rootAnimationLayer?.currentFrame = pauseFrame
addNewAnimationForContext(newContext)
}
func updateRasterizationState() {
if isAnimationPlaying {
animationLayer?.shouldRasterize = false
} else {
animationLayer?.shouldRasterize = shouldRasterizeWhenIdle
}
}
func loadAnimation(_ animationSource: LottieAnimationSource?) {
switch animationSource {
case .lottieAnimation(let animation):
self.animation = animation
case .dotLottieFile(let dotLottieFile):
loadAnimation(from: dotLottieFile)
case nil:
animation = nil
}
}
// MARK: Fileprivate
fileprivate var _activeAnimationName: String = LottieAnimationLayer.animationName
fileprivate var animationID = 0
fileprivate var activeAnimationName: String {
switch rootAnimationLayer?.primaryAnimationKey {
case .specific(let animationKey):
return animationKey
case .managed, nil:
return _activeAnimationName
}
}
/// Stops the current in flight animation and freezes the animation in its current state.
fileprivate func removeCurrentAnimation() {
guard animationContext != nil else { return }
let pauseFrame = realtimeAnimationFrame
animationLayer?.removeAnimation(forKey: activeAnimationName)
updateAnimationFrame(pauseFrame)
animationContext = nil
}
fileprivate func makeAnimationLayer(usingEngine renderingEngine: RenderingEngineOption) {
/// Disable the default implicit crossfade animation Core Animation creates
/// when adding or removing sublayers.
actions = ["sublayers": NSNull()]
/// Remove current animation if any
removeCurrentAnimation()
if let oldAnimation = animationLayer {
oldAnimation.removeFromSuperlayer()
rootAnimationLayer = nil
}
guard let animation else {
return
}
let rootAnimationLayer: RootAnimationLayer?
switch renderingEngine {
case .automatic:
rootAnimationLayer = makeAutomaticEngineLayer(for: animation)
case .specific(.coreAnimation):
rootAnimationLayer = makeCoreAnimationLayer(for: animation)
case .specific(.mainThread):
rootAnimationLayer = makeMainThreadAnimationLayer(for: animation)
}
guard let animationLayer = rootAnimationLayer else {
return
}
animationLayer.lottieAnimationLayer = self
for (keypath, valueProvider) in valueProviders {
animationLayer.setValueProvider(valueProvider, keypath: keypath)
}
animationLayerDidLoad?(self, renderingEngine)
animationLayer.renderScale = screenScale
addSublayer(animationLayer)
self.rootAnimationLayer = animationLayer
reloadImages()
animationLayer.setNeedsDisplay()
setNeedsLayout()
currentFrame = CGFloat(animation.startFrame)
}
fileprivate func makeMainThreadAnimationLayer(for animation: LottieAnimation) -> MainThreadAnimationLayer {
let mainThreadAnimationLayer = MainThreadAnimationLayer(
animation: animation,
imageProvider: imageProvider.cachedImageProvider,
textProvider: textProvider,
fontProvider: fontProvider,
maskAnimationToBounds: maskAnimationToBounds,
logger: logger)
mainThreadAnimationLayer.forceDisplayUpdateOnEachFrame = mainThreadRenderingEngineShouldForceDisplayUpdateOnEachFrame
return mainThreadAnimationLayer
}
fileprivate func makeCoreAnimationLayer(for animation: LottieAnimation) -> CoreAnimationLayer? {
do {
let coreAnimationLayer = try CoreAnimationLayer(
animation: animation,
imageProvider: imageProvider.cachedImageProvider,
textProvider: textProvider,
fontProvider: fontProvider,
maskAnimationToBounds: maskAnimationToBounds,
compatibilityTrackerMode: .track,
logger: logger)
coreAnimationLayer.didSetUpAnimation = { [logger] compatibilityIssues in
logger.assert(
compatibilityIssues.isEmpty,
"Encountered Core Animation compatibility issues while setting up animation:\n"
+ compatibilityIssues.map { $0.description }.joined(separator: "\n") + "\n\n"
+ """
This animation cannot be rendered correctly by the Core Animation engine.
To resolve this issue, you can use `RenderingEngineOption.automatic`, which automatically falls back
to the Main Thread rendering engine when necessary, or just use `RenderingEngineOption.mainThread`.
""")
}
return coreAnimationLayer
} catch {
// This should never happen, because we initialize the `CoreAnimationLayer` with
// `CompatibilityTracker.Mode.track` (which reports errors in `didSetUpAnimation`,
// not by throwing).
logger.assertionFailure("Encountered unexpected error \(error)")
return nil
}
}
fileprivate func makeAutomaticEngineLayer(for animation: LottieAnimation) -> CoreAnimationLayer? {
do {
// Attempt to set up the Core Animation layer. This can either throw immediately in `init`,
// or throw an error later in `CALayer.display()` that will be reported in `didSetUpAnimation`.
let coreAnimationLayer = try CoreAnimationLayer(
animation: animation,
imageProvider: imageProvider.cachedImageProvider,
textProvider: textProvider,
fontProvider: fontProvider,
maskAnimationToBounds: maskAnimationToBounds,
compatibilityTrackerMode: .abort,
logger: logger)
coreAnimationLayer.didSetUpAnimation = { [weak self] issues in
self?.automaticEngineLayerDidSetUpAnimation(issues)
}
return coreAnimationLayer
} catch {
if case CompatibilityTracker.Error.encounteredCompatibilityIssue(let compatibilityIssue) = error {
automaticEngineLayerDidSetUpAnimation([compatibilityIssue])
} else {
// This should never happen, because we expect `CoreAnimationLayer` to only throw
// `CompatibilityTracker.Error.encounteredCompatibilityIssue` errors.
logger.assertionFailure("Encountered unexpected error \(error)")
automaticEngineLayerDidSetUpAnimation([])
}
return nil
}
}
// Handles any compatibility issues with the Core Animation engine
// by falling back to the Main Thread engine
fileprivate func automaticEngineLayerDidSetUpAnimation(_ compatibilityIssues: [CompatibilityIssue]) {
// If there weren't any compatibility issues, then there's nothing else to do
if compatibilityIssues.isEmpty {
return
}
logger.warn(
"Encountered Core Animation compatibility issue while setting up animation:\n"
+ compatibilityIssues.map { $0.description }.joined(separator: "\n") + "\n"
+ """
This animation may have additional compatibility issues, but animation setup was cancelled early to avoid wasted work.
Automatically falling back to Main Thread rendering engine. This fallback comes with some additional performance
overhead, which can be reduced by manually specifying that this animation should always use the Main Thread engine.
""")
let animationContext = animationContext
let currentFrame = currentFrame
// Disable the completion handler delegate before tearing down the `CoreAnimationLayer`
// and building the `MainThreadAnimationLayer`. Otherwise deinitializing the
// `CoreAnimationLayer` would trigger the animation completion handler even though
// the animation hasn't even started playing yet.
animationContext?.closure.ignoreDelegate = true
makeAnimationLayer(usingEngine: .mainThread)
// Set up the Main Thread animation layer using the same configuration that
// was being used by the previous Core Animation layer
self.currentFrame = currentFrame
if let animationContext {
// `AnimationContext.closure` (`AnimationCompletionDelegate`) is a reference type
// that is the animation layer's `CAAnimationDelegate`, and holds a reference to
// the animation layer. Reusing a single instance across different animation layers
// can cause the animation setup to fail, so we create a copy of the `animationContext`:
addNewAnimationForContext(AnimationContext(
playFrom: animationContext.playFrom,
playTo: animationContext.playTo,
closure: animationContext.closure.completionBlock))
}
}
/// Removes the current animation and pauses the animation at the current frame
/// if necessary before setting up a new animation.
/// - This is not necessary with the Core Animation engine, and skipping
/// this step lets us avoid building the animations twice (once paused
/// and once again playing)
/// - This method should only be called immediately before setting up another
/// animation -- otherwise this LottieAnimationView could be put in an inconsistent state.
fileprivate func removeCurrentAnimationIfNecessary() {
switch currentRenderingEngine {
case .mainThread:
removeCurrentAnimation()
case .coreAnimation, nil:
// We still need to remove the `animationContext`, since it should only be present
// when an animation is actually playing. Without this calling `removeCurrentAnimationIfNecessary()`
// and then setting the animation to a specific paused frame would put this
// `LottieAnimationView` in an inconsistent state.
animationContext = nil
}
}
/// Adds animation to animation layer and sets the delegate. If animation layer or animation are nil, exits.
fileprivate func addNewAnimationForContext(_ animationContext: AnimationContext) {
guard let animationlayer = rootAnimationLayer, let animation else {
return
}
self.animationContext = animationContext
animationID = animationID + 1
_activeAnimationName = LottieAnimationLayer.animationName + String(animationID)
if let coreAnimationLayer = animationlayer as? CoreAnimationLayer {
var animationContext = animationContext
// Core Animation doesn't natively support negative speed values,
// so instead we can swap `playFrom` / `playTo`
if animationSpeed < 0 {
let temp = animationContext.playFrom
animationContext.playFrom = animationContext.playTo
animationContext.playTo = temp
}
var timingConfiguration = CoreAnimationLayer.CAMediaTimingConfiguration(
autoreverses: loopMode.caAnimationConfiguration.autoreverses,
repeatCount: loopMode.caAnimationConfiguration.repeatCount,
speed: abs(Float(animationSpeed)))
// The animation should start playing from the `currentFrame`,
// if `currentFrame` is included in the time range being played.
let lowerBoundTime = min(animationContext.playFrom, animationContext.playTo)
let upperBoundTime = max(animationContext.playFrom, animationContext.playTo)
if (lowerBoundTime ..< upperBoundTime).contains(round(currentFrame)) {
// We have to configure this differently depending on the loop mode:
switch loopMode {
// When playing exactly once (and not looping), we can just set the
// `playFrom` time to be the `currentFrame`. Since the animation duration
// is based on `playFrom` and `playTo`, this automatically truncates the
// duration (so the animation stops playing at `playFrom`).
// - Don't do this if the animation is already at that frame
// (e.g. playing from 100% to 0% when the animation is already at 0%)
// since that would cause the animation to not play at all.
case .playOnce:
if animationContext.playTo != currentFrame {
animationContext.playFrom = currentFrame
}
// When looping, we specifically _don't_ want to affect the duration of the animation,
// since that would affect the duration of all subsequent loops. We just want to adjust
// the duration of the _first_ loop. Instead of setting `playFrom`, we just add a `timeOffset`
// so the first loop begins at `currentTime` but all subsequent loops are the standard duration.
default:
if animationSpeed < 0 {
timingConfiguration.timeOffset = animation.time(forFrame: animationContext.playFrom) - currentTime
} else {
timingConfiguration.timeOffset = currentTime - animation.time(forFrame: animationContext.playFrom)
}
}
}
// If attempting to play a zero-duration animation, just pause on that single frame instead
if animationContext.playFrom == animationContext.playTo {
currentFrame = animationContext.playTo
animationContext.closure.completionBlock?(true)
return
}
coreAnimationLayer.playAnimation(configuration: .init(
animationContext: animationContext,
timingConfiguration: timingConfiguration))
return
}
/// At this point there is no animation on animationLayer and its state is set.
let framerate = animation.framerate
let playFrom = animationContext.playFrom.clamp(animation.startFrame, animation.endFrame)
let playTo = animationContext.playTo.clamp(animation.startFrame, animation.endFrame)
let duration = ((max(playFrom, playTo) - min(playFrom, playTo)) / CGFloat(framerate))
let playingForward: Bool =
(
(animationSpeed > 0 && playFrom < playTo) ||
(animationSpeed < 0 && playTo < playFrom))
var startFrame = currentFrame.clamp(min(playFrom, playTo), max(playFrom, playTo))
if startFrame == playTo {
startFrame = playFrom
}
let timeOffset: TimeInterval = playingForward
? Double(startFrame - min(playFrom, playTo)) / framerate
: Double(max(playFrom, playTo) - startFrame) / framerate
let layerAnimation = CABasicAnimation(keyPath: "currentFrame")
layerAnimation.fromValue = playFrom
layerAnimation.toValue = playTo
layerAnimation.speed = Float(animationSpeed)
layerAnimation.duration = TimeInterval(duration)
layerAnimation.fillMode = CAMediaTimingFillMode.both
layerAnimation.repeatCount = loopMode.caAnimationConfiguration.repeatCount
layerAnimation.autoreverses = loopMode.caAnimationConfiguration.autoreverses
layerAnimation.isRemovedOnCompletion = false
if timeOffset != 0 {
let currentLayerTime = convertTime(CACurrentMediaTime(), from: nil)
layerAnimation.beginTime = currentLayerTime - (timeOffset * 1 / Double(abs(animationSpeed)))
}
layerAnimation.delegate = animationContext.closure
animationContext.closure.animationLayer = animationlayer
animationContext.closure.animationKey = activeAnimationName
animationlayer.add(layerAnimation, forKey: activeAnimationName)
updateRasterizationState()
}
// MARK: Private
static private let animationName = "Lottie"
private let logger: LottieLogger
/// The `LottieBackgroundBehavior` that was specified manually by setting `self.backgroundBehavior`
private var _backgroundBehavior: LottieBackgroundBehavior?
/// Whether or not the current animation should be overridden with
/// the marker matching the current "reduced motion" mode.
private var shouldOverrideWithReducedMotionAnimation: Bool {
reducedMotionMarker != nil
}
/// The marker that corresponds to the current "reduced motion" mode.
private var reducedMotionMarker: Marker? {
switch configuration.reducedMotionOption.currentReducedMotionMode {
case .standardMotion:
return nil
case .reducedMotion:
return animation?.reducedMotionMarker
}
}
private func loadAnimation(_ dotLottieAnimation: DotLottieFile.Animation) {
loopMode = dotLottieAnimation.configuration.loopMode
animationSpeed = CGFloat(dotLottieAnimation.configuration.speed)
if let imageProvider = dotLottieAnimation.configuration.imageProvider {
self.imageProvider = imageProvider
}
animation = dotLottieAnimation.animation
}
/// Plays the marker that corresponds to the current "reduced motion" mode if present.
private func playReducedMotionAnimation(completion: LottieCompletionBlock?) {
guard let reducedMotionMarker else { return }
// `play(marker:)` calls the `play(fromFrame:toFrame:)` method which calls this
// `playReducedMotionAnimation` method when `shouldOverrideWithReducedMotionAnimation`
// is `true`. To prevent infinite recursion, disable the reduced motion functionality
// until the end of this function.
let currentConfiguration = configuration
configuration.reducedMotionOption = .standardMotion
defer { configuration = currentConfiguration }
play(marker: reducedMotionMarker.name, completion: completion)
}
}
// MARK: - LottieLoopMode + caAnimationConfiguration
extension LottieLoopMode {
/// The `CAAnimation` configuration that reflects this mode
var caAnimationConfiguration: (repeatCount: Float, autoreverses: Bool) {
switch self {
case .playOnce:
return (repeatCount: 1, autoreverses: false)
case .loop:
return (repeatCount: .greatestFiniteMagnitude, autoreverses: false)
case .autoReverse:
return (repeatCount: .greatestFiniteMagnitude, autoreverses: true)
case .repeat(let amount):
return (repeatCount: amount, autoreverses: false)
case .repeatBackwards(let amount):
return (repeatCount: amount, autoreverses: true)
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Animation/LottieAnimationLayer.swift
|
Swift
|
unknown
| 56,791
|
//
// LottieAnimationView.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/23/19.
//
import QuartzCore
// MARK: - LottieBackgroundBehavior
/// Describes the behavior of an AnimationView when the app is moved to the background.
public enum LottieBackgroundBehavior {
/// Stop the animation and reset it to the beginning of its current play time. The completion block is called.
case stop
/// Pause the animation in its current state. The completion block is called.
case pause
/// Pause the animation and restart it when the application moves to the foreground.
/// The completion block is stored and called when the animation completes.
/// - This is the default when using the Main Thread rendering engine.
case pauseAndRestore
/// Stops the animation and sets it to the end of its current play time. The completion block is called.
case forceFinish
/// The animation continues playing in the background.
/// - This is the default when using the Core Animation rendering engine.
/// Playing an animation using the Core Animation engine doesn't come with any CPU overhead,
/// so using `.continuePlaying` avoids the need to stop and then resume the animation
/// (which does come with some CPU overhead).
/// - This mode should not be used with the Main Thread rendering engine.
case continuePlaying
// MARK: Public
/// The default background behavior, based on the rendering engine being used to play the animation.
/// - Playing an animation using the Main Thread rendering engine comes with CPU overhead,
/// so the animation should be paused or stopped when the `LottieAnimationView` is not visible.
/// - Playing an animation using the Core Animation rendering engine does not come with any
/// CPU overhead, so these animations do not need to be paused in the background.
public static func `default`(for renderingEngine: RenderingEngine) -> LottieBackgroundBehavior {
switch renderingEngine {
case .mainThread:
return .pauseAndRestore
case .coreAnimation:
return .continuePlaying
}
}
}
// MARK: - LottieLoopMode
/// Defines animation loop behavior
public enum LottieLoopMode: Hashable {
/// Animation is played once then stops.
case playOnce
/// Animation will loop from beginning to end until stopped.
case loop
/// Animation will play forward, then backwards and loop until stopped.
case autoReverse
/// Animation will loop from beginning to end up to defined amount of times.
case `repeat`(Float)
/// Animation will play forward, then backwards a defined amount of times.
case repeatBackwards(Float)
}
// MARK: Equatable
extension LottieLoopMode: Equatable {
public static func == (lhs: LottieLoopMode, rhs: LottieLoopMode) -> Bool {
switch (lhs, rhs) {
case (.repeat(let lhsAmount), .repeat(let rhsAmount)),
(.repeatBackwards(let lhsAmount), .repeatBackwards(let rhsAmount)):
return lhsAmount == rhsAmount
case (.playOnce, .playOnce),
(.loop, .loop),
(.autoReverse, .autoReverse):
return true
default:
return false
}
}
}
// MARK: - LottieAnimationView
/// A UIView subclass for rendering Lottie animations.
/// - Also available as a SwiftUI view (`LottieView`) and a CALayer subclass (`LottieAnimationLayer`)
@IBDesignable
open class LottieAnimationView: LottieAnimationViewBase {
// MARK: Lifecycle
// MARK: - Public (Initializers)
/// Initializes an AnimationView with an animation.
public init(
animation: LottieAnimation?,
imageProvider: AnimationImageProvider? = nil,
textProvider: AnimationKeypathTextProvider = DefaultTextProvider(),
fontProvider: AnimationFontProvider = DefaultFontProvider(),
configuration: LottieConfiguration = .shared,
logger: LottieLogger = .shared)
{
lottieAnimationLayer = LottieAnimationLayer(
animation: animation,
imageProvider: imageProvider,
textProvider: textProvider,
fontProvider: fontProvider,
configuration: configuration,
logger: logger)
self.logger = logger
super.init(frame: .zero)
commonInit()
if let animation {
frame = animation.bounds
}
}
/// Initializes an AnimationView with a .lottie file.
public init(
dotLottie: DotLottieFile?,
animationId: String? = nil,
textProvider: AnimationKeypathTextProvider = DefaultTextProvider(),
fontProvider: AnimationFontProvider = DefaultFontProvider(),
configuration: LottieConfiguration = .shared,
logger: LottieLogger = .shared)
{
lottieAnimationLayer = LottieAnimationLayer(
dotLottie: dotLottie,
animationId: animationId,
textProvider: textProvider,
fontProvider: fontProvider,
configuration: configuration,
logger: logger)
self.logger = logger
super.init(frame: .zero)
commonInit()
if let animation {
frame = animation.bounds
}
}
public init(
configuration: LottieConfiguration = .shared,
logger: LottieLogger = .shared)
{
lottieAnimationLayer = LottieAnimationLayer(configuration: configuration, logger: logger)
self.logger = logger
super.init(frame: .zero)
commonInit()
}
public override init(frame: CGRect) {
lottieAnimationLayer = LottieAnimationLayer(
animation: nil,
imageProvider: BundleImageProvider(bundle: Bundle.main, searchPath: nil),
textProvider: DefaultTextProvider(),
fontProvider: DefaultFontProvider(),
configuration: .shared,
logger: .shared)
logger = .shared
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
lottieAnimationLayer = LottieAnimationLayer(
animation: nil,
imageProvider: BundleImageProvider(bundle: Bundle.main, searchPath: nil),
textProvider: DefaultTextProvider(),
fontProvider: DefaultFontProvider(),
configuration: .shared,
logger: .shared)
logger = .shared
super.init(coder: aDecoder)
commonInit()
}
convenience init(
animationSource: LottieAnimationSource?,
imageProvider: AnimationImageProvider? = nil,
textProvider: AnimationKeypathTextProvider = DefaultTextProvider(),
fontProvider: AnimationFontProvider = DefaultFontProvider(),
configuration: LottieConfiguration = .shared,
logger: LottieLogger = .shared)
{
switch animationSource {
case .lottieAnimation(let animation):
self.init(
animation: animation,
imageProvider: imageProvider,
textProvider: textProvider,
fontProvider: fontProvider,
configuration: configuration,
logger: logger)
case .dotLottieFile(let dotLottieFile):
self.init(
dotLottie: dotLottieFile,
textProvider: textProvider,
fontProvider: fontProvider,
configuration: configuration,
logger: logger)
case nil:
self.init(
animation: nil,
imageProvider: imageProvider,
textProvider: textProvider,
fontProvider: fontProvider,
configuration: configuration,
logger: logger)
}
}
// MARK: Open
/// Applies the given `LottiePlaybackMode` to this layer.
/// - Parameter completion: A closure that is called after
/// an animation triggered by this method completes.
open func play(_ mode: LottiePlaybackMode.PlaybackMode, completion: LottieCompletionBlock? = nil) {
lottieAnimationLayer.play(mode, completion: completion)
}
/// Plays the animation from its current state to the end.
///
/// - Parameter completion: An optional completion closure to be called when the animation completes playing.
open func play(completion: LottieCompletionBlock? = nil) {
lottieAnimationLayer.play(completion: completion)
}
/// Plays the animation from a progress (0-1) to a progress (0-1).
///
/// - Parameter fromProgress: The start progress of the animation. If `nil` the animation will start at the current progress.
/// - Parameter toProgress: The end progress of the animation.
/// - Parameter loopMode: The loop behavior of the animation. If `nil` the view's `loopMode` property will be used.
/// - Parameter completion: An optional completion closure to be called when the animation stops.
open func play(
fromProgress: AnimationProgressTime? = nil,
toProgress: AnimationProgressTime,
loopMode: LottieLoopMode? = nil,
completion: LottieCompletionBlock? = nil)
{
lottieAnimationLayer.play(fromProgress: fromProgress, toProgress: toProgress, loopMode: loopMode, completion: completion)
}
/// Plays the animation from a start frame to an end frame in the animation's framerate.
///
/// - Parameter fromFrame: The start frame of the animation. If `nil` the animation will start at the current frame.
/// - Parameter toFrame: The end frame of the animation.
/// - Parameter loopMode: The loop behavior of the animation. If `nil` the view's `loopMode` property will be used.
/// - Parameter completion: An optional completion closure to be called when the animation stops.
open func play(
fromFrame: AnimationFrameTime? = nil,
toFrame: AnimationFrameTime,
loopMode: LottieLoopMode? = nil,
completion: LottieCompletionBlock? = nil)
{
lottieAnimationLayer.play(fromFrame: fromFrame, toFrame: toFrame, loopMode: loopMode, completion: completion)
}
/// Plays the animation from a named marker to another marker.
///
/// Markers are point in time that are encoded into the Animation data and assigned
/// a name.
///
/// NOTE: If markers are not found the play command will exit.
///
/// - Parameter fromMarker: The start marker for the animation playback. If `nil` the
/// animation will start at the current progress.
/// - Parameter toMarker: The end marker for the animation playback.
/// - Parameter playEndMarkerFrame: A flag to determine whether or not to play the frame of the end marker. If the
/// end marker represents the end of the section to play, it should be to true. If the provided end marker
/// represents the beginning of the next section, it should be false.
/// - Parameter loopMode: The loop behavior of the animation. If `nil` the view's `loopMode` property will be used.
/// - Parameter completion: An optional completion closure to be called when the animation stops.
open func play(
fromMarker: String? = nil,
toMarker: String,
playEndMarkerFrame: Bool = true,
loopMode: LottieLoopMode? = nil,
completion: LottieCompletionBlock? = nil)
{
lottieAnimationLayer.play(
fromMarker: fromMarker,
toMarker: toMarker,
playEndMarkerFrame: playEndMarkerFrame,
loopMode: loopMode,
completion: completion)
}
/// Plays the animation from a named marker to the end of the marker's duration.
///
/// A marker is a point in time with an associated duration that is encoded into the
/// animation data and assigned a name.
///
/// NOTE: If marker is not found the play command will exit.
///
/// - Parameter marker: The start marker for the animation playback.
/// - Parameter loopMode: The loop behavior of the animation. If `nil` the view's `loopMode` property will be used.
/// - Parameter completion: An optional completion closure to be called when the animation stops.
open func play(
marker: String,
loopMode: LottieLoopMode? = nil,
completion: LottieCompletionBlock? = nil)
{
lottieAnimationLayer.play(marker: marker, loopMode: loopMode, completion: completion)
}
/// Plays the given markers sequentially in order.
///
/// A marker is a point in time with an associated duration that is encoded into the
/// animation data and assigned a name. Multiple markers can be played sequentially
/// to create programmable animations.
///
/// If a marker is not found, it will be skipped.
///
/// If a marker doesn't have a duration value, it will play with a duration of 0
/// (effectively being skipped).
///
/// If another animation is played (by calling any `play` method) while this
/// marker sequence is playing, the marker sequence will be cancelled.
///
/// - Parameter markers: The list of markers to play sequentially.
/// - Parameter completion: An optional completion closure to be called when the animation stops.
open func play(
markers: [String],
completion: LottieCompletionBlock? = nil)
{
lottieAnimationLayer.play(markers: markers, completion: completion)
}
/// Stops the animation and resets the view to its start frame.
///
/// The completion closure will be called with `false`
open func stop() {
lottieAnimationLayer.stop()
}
/// Pauses the animation in its current state.
///
/// The completion closure will be called with `false`
open func pause() {
lottieAnimationLayer.pause()
}
@available(*, deprecated, renamed: "setPlaybackMode(_:completion:)", message: "Will be removed in a future major release.")
open func play(
_ playbackMode: LottiePlaybackMode,
animationCompletionHandler: LottieCompletionBlock? = nil)
{
lottieAnimationLayer.setPlaybackMode(playbackMode, completion: animationCompletionHandler)
}
/// Applies the given `LottiePlaybackMode` to this layer.
/// - Parameter completion: A closure that is called after
/// an animation triggered by this method completes.
open func setPlaybackMode(
_ playbackMode: LottiePlaybackMode,
completion: LottieCompletionBlock? = nil)
{
lottieAnimationLayer.setPlaybackMode(playbackMode, completion: completion)
}
// MARK: Public
/// Whether or not transform and position changes of the view should animate alongside
/// any existing animation context.
/// - Defaults to `true` which will grab the current animation context and animate position and
/// transform changes matching the current context's curve and duration.
/// `false` will cause transform and position changes to happen unanimated
public var animateLayoutChangesWithCurrentCoreAnimationContext = true
/// The configuration that this `LottieAnimationView` uses when playing its animation
public var configuration: LottieConfiguration {
get { lottieAnimationLayer.configuration }
set { lottieAnimationLayer.configuration = newValue }
}
/// Value Providers that have been registered using `setValueProvider(_:keypath:)`
public var valueProviders: [AnimationKeypath: AnyValueProvider] {
lottieAnimationLayer.valueProviders
}
/// Describes the behavior of an AnimationView when the app is moved to the background.
///
/// The default for the Main Thread animation engine is `pause`,
/// which pauses the animation when the application moves to
/// the background. This prevents the animation from consuming CPU
/// resources when not on-screen. The completion block is called with
/// `false` for completed.
///
/// The default for the Core Animation engine is `continuePlaying`,
/// since the Core Animation engine does not have any CPU overhead.
public var backgroundBehavior: LottieBackgroundBehavior {
get { lottieAnimationLayer.backgroundBehavior }
set { lottieAnimationLayer.backgroundBehavior = newValue }
}
/// Sets the animation backing the animation view. Setting this will clear the
/// view's contents, completion blocks and current state. The new animation will
/// be loaded up and set to the beginning of its timeline.
public var animation: LottieAnimation? {
get { lottieAnimationLayer.animation }
set { lottieAnimationLayer.animation = newValue }
}
/// A closure that is called when `self.animation` is loaded. When setting this closure,
/// it is called immediately if `self.animation` is non-nil.
///
/// When initializing a `LottieAnimationView`, the animation will either be loaded
/// synchronously (when loading a `LottieAnimation` from a .json file on disk)
/// or asynchronously (when loading a `DotLottieFile` from disk, or downloading
/// an animation from a URL). This closure is called in both cases once the
/// animation is loaded and applied, so can be a useful way to configure this
/// `LottieAnimationView` regardless of which initializer was used. For example:
///
/// ```
/// let animationView: LottieAnimationView
///
/// if loadDotLottieFile {
/// // Loads the .lottie file asynchronously
/// animationView = LottieAnimationView(dotLottieName: "animation")
/// } else {
/// // Loads the .json file synchronously
/// animationView = LottieAnimationView(name: "animation")
/// }
///
/// animationView.animationLoaded = { animationView, animation in
/// // If using a .lottie file, this is called once the file finishes loading.
/// // If using a .json file, this is called immediately (since the animation is loaded synchronously).
/// animationView.play()
/// }
/// ```
public var animationLoaded: ((_ animationView: LottieAnimationView, _ animation: LottieAnimation) -> Void)? {
didSet {
if let animation {
animationLoaded?(self, animation)
}
}
}
/// Sets the image provider for the animation view. An image provider provides the
/// animation with its required image data.
///
/// Setting this will cause the animation to reload its image contents.
public var imageProvider: AnimationImageProvider {
get { lottieAnimationLayer.imageProvider }
set { lottieAnimationLayer.imageProvider = newValue }
}
/// Sets the text provider for animation view. A text provider provides the
/// animation with values for text layers
public var textProvider: AnimationKeypathTextProvider {
get { lottieAnimationLayer.textProvider }
set { lottieAnimationLayer.textProvider = newValue }
}
/// Sets the text provider for animation view. A text provider provides the
/// animation with values for text layers
public var fontProvider: AnimationFontProvider {
get { lottieAnimationLayer.fontProvider }
set { lottieAnimationLayer.fontProvider = newValue }
}
/// Whether or not the animation is masked to the bounds. Defaults to true.
public var maskAnimationToBounds: Bool {
get { lottieAnimationLayer.maskAnimationToBounds }
set { lottieAnimationLayer.maskAnimationToBounds = newValue }
}
/// Returns `true` if the animation is currently playing.
public var isAnimationPlaying: Bool {
lottieAnimationLayer.isAnimationPlaying
}
/// Returns `true` if the animation will start playing when this view is added to a window.
public var isAnimationQueued: Bool {
lottieAnimationLayer.hasAnimationContext && waitingToPlayAnimation
}
/// Sets the loop behavior for `play` calls. Defaults to `playOnce`
public var loopMode: LottieLoopMode {
get { lottieAnimationLayer.loopMode }
set { lottieAnimationLayer.loopMode = newValue }
}
/// When `true` the animation view will rasterize its contents when not animating.
/// Rasterizing will improve performance of static animations.
///
/// Note: this will not produce crisp results at resolutions above the animations natural resolution.
///
/// Defaults to `false`
public var shouldRasterizeWhenIdle: Bool {
get { lottieAnimationLayer.shouldRasterizeWhenIdle }
set { lottieAnimationLayer.shouldRasterizeWhenIdle = newValue }
}
/// Sets the current animation time with a Progress Time
///
/// Note: Setting this will stop the current animation, if any.
/// Note 2: If `animation` is nil, setting this will fallback to 0
public var currentProgress: AnimationProgressTime {
get { lottieAnimationLayer.currentProgress }
set { lottieAnimationLayer.currentProgress = newValue }
}
/// Sets the current animation time with a time in seconds.
///
/// Note: Setting this will stop the current animation, if any.
/// Note 2: If `animation` is nil, setting this will fallback to 0
public var currentTime: TimeInterval {
get { lottieAnimationLayer.currentTime }
set { lottieAnimationLayer.currentTime = newValue }
}
/// Sets the current animation time with a frame in the animations framerate.
///
/// Note: Setting this will stop the current animation, if any.
public var currentFrame: AnimationFrameTime {
get { lottieAnimationLayer.currentFrame }
set { lottieAnimationLayer.currentFrame = newValue }
}
/// Returns the current animation frame while an animation is playing.
public var realtimeAnimationFrame: AnimationFrameTime {
lottieAnimationLayer.realtimeAnimationFrame
}
/// Returns the current animation frame while an animation is playing.
public var realtimeAnimationProgress: AnimationProgressTime {
lottieAnimationLayer.realtimeAnimationProgress
}
/// Sets the speed of the animation playback. Defaults to 1
public var animationSpeed: CGFloat {
get { lottieAnimationLayer.animationSpeed }
set { lottieAnimationLayer.animationSpeed = newValue }
}
/// When `true` the animation will play back at the framerate encoded in the
/// `LottieAnimation` model. When `false` the animation will play at the framerate
/// of the device.
///
/// Defaults to false
public var respectAnimationFrameRate: Bool {
get { lottieAnimationLayer.respectAnimationFrameRate }
set { lottieAnimationLayer.respectAnimationFrameRate = newValue }
}
/// Controls the cropping of an Animation. Setting this property will crop the animation
/// to the current views bounds by the viewport frame. The coordinate space is specified
/// in the animation's coordinate space.
///
/// Animatable.
public var viewportFrame: CGRect? {
didSet {
// This is really ugly, but is needed to trigger a layout pass within an animation block.
// Typically this happens automatically, when layout objects are UIView based.
// The animation layer is a CALayer which will not implicitly grab the animation
// duration of a UIView animation block.
//
// By setting bounds and then resetting bounds the UIView animation block's
// duration and curve are captured and added to the layer. This is used in the
// layout block to animate the animationLayer's position and size.
let rect = bounds
self.bounds = CGRect.zero
self.bounds = rect
self.setNeedsLayout()
}
}
override public var intrinsicContentSize: CGSize {
if let animation = lottieAnimationLayer.animation {
return animation.bounds.size
}
return .zero
}
/// The rendering engine currently being used by this view.
/// - This will only be `nil` in cases where the configuration is `automatic`
/// but a `RootAnimationLayer` hasn't been constructed yet
public var currentRenderingEngine: RenderingEngine? {
lottieAnimationLayer.currentRenderingEngine
}
/// The current `LottiePlaybackMode` that is being used
public var currentPlaybackMode: LottiePlaybackMode? {
lottieAnimationLayer.currentPlaybackMode
}
/// Whether or not the Main Thread rendering engine should use `forceDisplayUpdate()`
/// when rendering each individual frame.
/// - The main thread rendering engine implements optimizations to decrease the amount
/// of properties that have to be re-rendered on each frame. There are some cases
/// where this can result in bugs / incorrect behavior, so we allow it to be disabled.
/// - Forcing a full render on every frame will decrease performance, and is not recommended
/// except as a workaround to a bug in the main thread rendering engine.
/// - Has no effect when using the Core Animation rendering engine.
public var mainThreadRenderingEngineShouldForceDisplayUpdateOnEachFrame: Bool {
get { lottieAnimationLayer.mainThreadRenderingEngineShouldForceDisplayUpdateOnEachFrame }
set { lottieAnimationLayer.mainThreadRenderingEngineShouldForceDisplayUpdateOnEachFrame = newValue }
}
/// Sets the lottie file backing the animation view. Setting this will clear the
/// view's contents, completion blocks and current state. The new animation will
/// be loaded up and set to the beginning of its timeline.
/// The loopMode, animationSpeed and imageProvider will be set according
/// to lottie file settings
/// - Parameters:
/// - animationId: Internal animation id to play. Optional
/// Defaults to play first animation in file.
/// - dotLottieFile: Lottie file to play
public func loadAnimation(
_ animationId: String? = nil,
from dotLottieFile: DotLottieFile)
{
lottieAnimationLayer.loadAnimation(animationId, from: dotLottieFile)
}
/// Sets the lottie file backing the animation view. Setting this will clear the
/// view's contents, completion blocks and current state. The new animation will
/// be loaded up and set to the beginning of its timeline.
/// The loopMode, animationSpeed and imageProvider will be set according
/// to lottie file settings
/// - Parameters:
/// - atIndex: Internal animation index to play. Optional
/// Defaults to play first animation in file.
/// - dotLottieFile: Lottie file to play
public func loadAnimation(
atIndex index: Int,
from dotLottieFile: DotLottieFile)
{
lottieAnimationLayer.loadAnimation(atIndex: index, from: dotLottieFile)
}
/// Reloads the images supplied to the animation from the `imageProvider`
public func reloadImages() {
lottieAnimationLayer.reloadImages()
}
/// Forces the LottieAnimationView to redraw its contents.
public func forceDisplayUpdate() {
lottieAnimationLayer.forceDisplayUpdate()
}
/// Sets a ValueProvider for the specified keypath. The value provider will be set
/// on all properties that match the keypath.
///
/// Nearly all properties of a Lottie animation can be changed at runtime using a
/// combination of `Animation Keypaths` and `Value Providers`.
/// Setting a ValueProvider on a keypath will cause the animation to update its
/// contents and read the new Value Provider.
///
/// A value provider provides a typed value on a frame by frame basis.
///
/// - Parameter valueProvider: The new value provider for the properties.
/// - Parameter keypath: The keypath used to search for properties.
///
/// Example:
/// ```
/// /// A keypath that finds the color value for all `Fill 1` nodes.
/// let fillKeypath = AnimationKeypath(keypath: "**.Fill 1.Color")
/// /// A Color Value provider that returns a reddish color.
/// let redValueProvider = ColorValueProvider(Color(r: 1, g: 0.2, b: 0.3, a: 1))
/// /// Set the provider on the animationView.
/// animationView.setValueProvider(redValueProvider, keypath: fillKeypath)
/// ```
public func setValueProvider(_ valueProvider: AnyValueProvider, keypath: AnimationKeypath) {
lottieAnimationLayer.setValueProvider(valueProvider, keypath: keypath)
}
/// Reads the value of a property specified by the Keypath.
/// Returns nil if no property is found.
///
/// - Parameter for: The keypath used to search for the property.
/// - Parameter atFrame: The Frame Time of the value to query. If nil then the current frame is used.
public func getValue(for keypath: AnimationKeypath, atFrame: AnimationFrameTime?) -> Any? {
lottieAnimationLayer.getValue(for: keypath, atFrame: atFrame)
}
/// Reads the original value of a property specified by the Keypath.
/// This will ignore any value providers and can be useful when implementing a value providers that makes change to the original value from the animation.
/// Returns nil if no property is found.
///
/// - Parameter for: The keypath used to search for the property.
/// - Parameter atFrame: The Frame Time of the value to query. If nil then the current frame is used.
public func getOriginalValue(for keypath: AnimationKeypath, atFrame: AnimationFrameTime?) -> Any? {
lottieAnimationLayer.getOriginalValue(for: keypath, atFrame: atFrame)
}
/// Logs all child keypaths.
/// Logs the result of `allHierarchyKeypaths()` to the `LottieLogger`.
public func logHierarchyKeypaths() {
lottieAnimationLayer.logHierarchyKeypaths()
}
/// Computes and returns a list of all child keypaths in the current animation.
/// The returned list is the same as the log output of `logHierarchyKeypaths()`
public func allHierarchyKeypaths() -> [String] {
lottieAnimationLayer.allHierarchyKeypaths()
}
/// Searches for the nearest child layer to the first Keypath and adds the subview
/// to that layer. The subview will move and animate with the child layer.
/// Furthermore the subview will be in the child layers coordinate space.
///
/// Note: if no layer is found for the keypath, then nothing happens.
///
/// - Parameter subview: The subview to add to the found animation layer.
/// - Parameter keypath: The keypath used to find the animation layer.
///
/// Example:
/// ```
/// /// A keypath that finds `Layer 1`
/// let layerKeypath = AnimationKeypath(keypath: "Layer 1")
///
/// /// Wrap the custom view in an `AnimationSubview`
/// let subview = AnimationSubview()
/// subview.addSubview(customView)
///
/// /// Set the provider on the animationView.
/// animationView.addSubview(subview, forLayerAt: layerKeypath)
/// ```
public func addSubview(_ subview: AnimationSubview, forLayerAt keypath: AnimationKeypath) {
guard let sublayer = lottieAnimationLayer.rootAnimationLayer?.layer(for: keypath) else {
return
}
setNeedsLayout()
layoutIfNeeded()
lottieAnimationLayer.forceDisplayUpdate()
addSubview(subview)
if let subViewLayer = subview.viewLayer {
sublayer.addSublayer(subViewLayer)
}
}
/// Converts a CGRect from the LottieAnimationView's coordinate space into the
/// coordinate space of the layer found at Keypath.
///
/// If no layer is found, nil is returned
///
/// - Parameter rect: The CGRect to convert.
/// - Parameter toLayerAt: The keypath used to find the layer.
public func convert(_ rect: CGRect, toLayerAt keypath: AnimationKeypath?) -> CGRect? {
let convertedRect = lottieAnimationLayer.convert(rect, toLayerAt: keypath)
setNeedsLayout()
layoutIfNeeded()
return convertedRect
}
/// Converts a CGPoint from the LottieAnimationView's coordinate space into the
/// coordinate space of the layer found at Keypath.
///
/// If no layer is found, nil is returned
///
/// - Parameter point: The CGPoint to convert.
/// - Parameter toLayerAt: The keypath used to find the layer.
public func convert(_ point: CGPoint, toLayerAt keypath: AnimationKeypath?) -> CGPoint? {
let convertedRect = lottieAnimationLayer.convert(point, toLayerAt: keypath)
setNeedsLayout()
layoutIfNeeded()
return convertedRect
}
/// Sets the enabled state of all animator nodes found with the keypath search.
/// This can be used to interactively enable / disable parts of the animation.
///
/// - Parameter isEnabled: When true the animator nodes affect the rendering tree. When false the node is removed from the tree.
/// - Parameter keypath: The keypath used to find the node(s).
public func setNodeIsEnabled(isEnabled: Bool, keypath: AnimationKeypath) {
lottieAnimationLayer.setNodeIsEnabled(isEnabled: isEnabled, keypath: keypath)
}
/// Markers are a way to describe a point in time by a key name.
///
/// Markers are encoded into animation JSON. By using markers a designer can mark
/// playback points for a developer to use without having to worry about keeping
/// track of animation frames. If the animation file is updated, the developer
/// does not need to update playback code.
///
/// Returns the Progress Time for the marker named. Returns nil if no marker found.
public func progressTime(forMarker named: String) -> AnimationProgressTime? {
lottieAnimationLayer.progressTime(forMarker: named)
}
/// Markers are a way to describe a point in time by a key name.
///
/// Markers are encoded into animation JSON. By using markers a designer can mark
/// playback points for a developer to use without having to worry about keeping
/// track of animation frames. If the animation file is updated, the developer
/// does not need to update playback code.
///
/// Returns the Frame Time for the marker named. Returns nil if no marker found.
public func frameTime(forMarker named: String) -> AnimationFrameTime? {
lottieAnimationLayer.frameTime(forMarker: named)
}
/// Markers are a way to describe a point in time and a duration by a key name.
///
/// Markers are encoded into animation JSON. By using markers a designer can mark
/// playback points for a developer to use without having to worry about keeping
/// track of animation frames. If the animation file is updated, the developer
/// does not need to update playback code.
///
/// - Returns: The duration frame time for the marker, or `nil` if no marker found.
public func durationFrameTime(forMarker named: String) -> AnimationFrameTime? {
lottieAnimationLayer.durationFrameTime(forMarker: named)
}
// MARK: Internal
// The backing CALayer for this animation view.
let lottieAnimationLayer: LottieAnimationLayer
var animationLayer: RootAnimationLayer? {
lottieAnimationLayer.rootAnimationLayer
}
/// Set animation name from Interface Builder
@IBInspectable var animationName: String? {
didSet {
self.lottieAnimationLayer.animation = animationName.flatMap { LottieAnimation.named($0, animationCache: nil)
}
}
}
override func commonInit() {
super.commonInit()
lottieAnimationLayer.screenScale = screenScale
viewLayer?.addSublayer(lottieAnimationLayer)
lottieAnimationLayer.animationLoaded = { [weak self] _, animation in
guard let self else { return }
self.animationLoaded?(self, animation)
self.invalidateIntrinsicContentSize()
self.setNeedsLayout()
}
lottieAnimationLayer.animationLayerDidLoad = { [weak self] _, _ in
guard let self else { return }
self.invalidateIntrinsicContentSize()
self.setNeedsLayout()
}
}
override func layoutAnimation() {
guard let animation = lottieAnimationLayer.animation, let animationLayer = lottieAnimationLayer.animationLayer else { return }
var position = animation.bounds.center
let xform: CATransform3D
var shouldForceUpdates = false
if let viewportFrame {
shouldForceUpdates = contentMode == .redraw
let compAspect = viewportFrame.size.width / viewportFrame.size.height
let viewAspect = bounds.size.width / bounds.size.height
let dominantDimension = compAspect > viewAspect ? bounds.size.width : bounds.size.height
let compDimension = compAspect > viewAspect ? viewportFrame.size.width : viewportFrame.size.height
let scale = dominantDimension / compDimension
let viewportOffset = animation.bounds.center - viewportFrame.center
xform = CATransform3DTranslate(CATransform3DMakeScale(scale, scale, 1), viewportOffset.x, viewportOffset.y, 0)
position = bounds.center
} else {
switch contentMode {
case .scaleToFill:
position = bounds.center
xform = CATransform3DMakeScale(
bounds.size.width / animation.size.width,
bounds.size.height / animation.size.height,
1)
case .scaleAspectFit:
position = bounds.center
let compAspect = animation.size.width / animation.size.height
let viewAspect = bounds.size.width / bounds.size.height
let dominantDimension = compAspect > viewAspect ? bounds.size.width : bounds.size.height
let compDimension = compAspect > viewAspect ? animation.size.width : animation.size.height
let scale = dominantDimension / compDimension
xform = CATransform3DMakeScale(scale, scale, 1)
case .scaleAspectFill:
position = bounds.center
let compAspect = animation.size.width / animation.size.height
let viewAspect = bounds.size.width / bounds.size.height
let scaleWidth = compAspect < viewAspect
let dominantDimension = scaleWidth ? bounds.size.width : bounds.size.height
let compDimension = scaleWidth ? animation.size.width : animation.size.height
let scale = dominantDimension / compDimension
xform = CATransform3DMakeScale(scale, scale, 1)
case .redraw:
shouldForceUpdates = true
xform = CATransform3DIdentity
case .center:
position = bounds.center
xform = CATransform3DIdentity
case .top:
position.x = bounds.center.x
xform = CATransform3DIdentity
case .bottom:
position.x = bounds.center.x
position.y = bounds.maxY - animation.bounds.midY
xform = CATransform3DIdentity
case .left:
position.y = bounds.center.y
xform = CATransform3DIdentity
case .right:
position.y = bounds.center.y
position.x = bounds.maxX - animation.bounds.midX
xform = CATransform3DIdentity
case .topLeft:
xform = CATransform3DIdentity
case .topRight:
position.x = bounds.maxX - animation.bounds.midX
xform = CATransform3DIdentity
case .bottomLeft:
position.y = bounds.maxY - animation.bounds.midY
xform = CATransform3DIdentity
case .bottomRight:
position.x = bounds.maxX - animation.bounds.midX
position.y = bounds.maxY - animation.bounds.midY
xform = CATransform3DIdentity
#if canImport(UIKit)
@unknown default:
logger.assertionFailure("unsupported contentMode: \(contentMode.rawValue)")
xform = CATransform3DIdentity
#endif
}
}
// UIView Animation does not implicitly set CAAnimation time or timing fuctions.
// If layout is changed in an animation we must get the current animation duration
// and timing function and then manually create a CAAnimation to match the UIView animation.
// If layout is changed without animation, explicitly set animation duration to 0.0
// inside CATransaction to avoid unwanted artifacts.
/// Check if any animation exist on the view's layer, and match it.
if
let key = lottieAnimationLayer.animationKeys()?.first,
let animation = lottieAnimationLayer.animation(forKey: key),
animateLayoutChangesWithCurrentCoreAnimationContext
{
// The layout is happening within an animation block. Grab the animation data.
let positionKey = "LayoutPositionAnimation"
let transformKey = "LayoutTransformAnimation"
animationLayer.removeAnimation(forKey: positionKey)
animationLayer.removeAnimation(forKey: transformKey)
let positionAnimation = animation.copy() as? CABasicAnimation ?? CABasicAnimation(keyPath: "position")
positionAnimation.keyPath = "position"
positionAnimation.isAdditive = false
positionAnimation.fromValue = (animationLayer.presentation() ?? animationLayer).position
positionAnimation.toValue = position
positionAnimation.isRemovedOnCompletion = true
let xformAnimation = animation.copy() as? CABasicAnimation ?? CABasicAnimation(keyPath: "transform")
xformAnimation.keyPath = "transform"
xformAnimation.isAdditive = false
xformAnimation.fromValue = (animationLayer.presentation() ?? animationLayer).transform
xformAnimation.toValue = xform
xformAnimation.isRemovedOnCompletion = true
animationLayer.position = position
animationLayer.transform = xform
animationLayer.anchorPoint = lottieAnimationLayer.anchorPoint
animationLayer.add(positionAnimation, forKey: positionKey)
animationLayer.add(xformAnimation, forKey: transformKey)
} else {
// In performance tests, we have to wrap the animation view setup
// in a `CATransaction` in order for the layers to be deallocated at
// the correct time. The `CATransaction`s in this method interfere
// with the ones managed by the performance test, and aren't actually
// necessary in a headless environment, so we disable them.
if TestHelpers.performanceTestsAreRunning {
animationLayer.position = position
animationLayer.transform = xform
} else {
CATransaction.begin()
CATransaction.setAnimationDuration(0.0)
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: .linear))
animationLayer.position = position
animationLayer.transform = xform
CATransaction.commit()
}
}
if shouldForceUpdates {
lottieAnimationLayer.forceDisplayUpdate()
}
}
func updateRasterizationState() {
lottieAnimationLayer.updateRasterizationState()
}
/// Updates the animation frame. Does not affect any current animations
func updateAnimationFrame(_ newFrame: CGFloat) {
lottieAnimationLayer.updateAnimationFrame(newFrame)
}
@objc
override func animationWillMoveToBackground() {
updateAnimationForBackgroundState()
}
@objc
override func animationWillEnterForeground() {
updateAnimationForForegroundState()
}
override func animationMovedToWindow() {
/// Don't update any state if the `superview` is `nil`
/// When A viewA owns superViewB, it removes the superViewB from the window. At this point, viewA still owns superViewB and triggers the viewA method: -didmovetowindow
guard superview != nil else { return }
if window != nil {
updateAnimationForForegroundState()
} else {
updateAnimationForBackgroundState()
}
}
func updateInFlightAnimation() {
lottieAnimationLayer.updateInFlightAnimation()
}
func loadAnimation(_ animationSource: LottieAnimationSource?) {
lottieAnimationLayer.loadAnimation(animationSource)
}
// MARK: Fileprivate
fileprivate var waitingToPlayAnimation = false
fileprivate func updateAnimationForBackgroundState() {
lottieAnimationLayer.updateAnimationForBackgroundState()
}
fileprivate func updateAnimationForForegroundState() {
let wasWaitingToPlayAnimation = waitingToPlayAnimation
if waitingToPlayAnimation {
waitingToPlayAnimation = false
}
lottieAnimationLayer.updateAnimationForForegroundState(wasWaitingToPlayAnimation: wasWaitingToPlayAnimation)
}
// MARK: Private
private let logger: LottieLogger
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Animation/LottieAnimationView.swift
|
Swift
|
unknown
| 42,459
|
//
// AnimationViewInitializers.swift
// lottie-swift-iOS
//
// Created by Brandon Withrow on 2/6/19.
//
import Foundation
extension LottieAnimationView {
// MARK: Lifecycle
/// Loads a Lottie animation from a JSON file in the supplied bundle.
///
/// - Parameter name: The string name of the lottie animation with no file extension provided.
/// - Parameter bundle: The bundle in which the animation is located. Defaults to the Main bundle.
/// - Parameter subdirectory: A subdirectory in the bundle in which the animation is located. Optional.
/// - Parameter imageProvider: An image provider for the animation's image data.
/// If none is supplied Lottie will search in the supplied bundle for images.
public convenience init(
name: String,
bundle: Bundle = Bundle.main,
subdirectory: String? = nil,
imageProvider: AnimationImageProvider? = nil,
animationCache: AnimationCacheProvider? = LottieAnimationCache.shared,
configuration: LottieConfiguration = .shared)
{
let animation = LottieAnimation.named(name, bundle: bundle, subdirectory: subdirectory, animationCache: animationCache)
let provider = imageProvider ?? BundleImageProvider(bundle: bundle, searchPath: nil)
self.init(animation: animation, imageProvider: provider, configuration: configuration)
}
/// Loads a Lottie animation from a JSON file in a specific path on disk.
///
/// - Parameter name: The absolute path of the Lottie Animation.
/// - Parameter imageProvider: An image provider for the animation's image data.
/// If none is supplied Lottie will search in the supplied filepath for images.
public convenience init(
filePath: String,
imageProvider: AnimationImageProvider? = nil,
animationCache: AnimationCacheProvider? = LottieAnimationCache.shared,
configuration: LottieConfiguration = .shared)
{
let animation = LottieAnimation.filepath(filePath, animationCache: animationCache)
let provider = imageProvider ??
FilepathImageProvider(filepath: URL(fileURLWithPath: filePath).deletingLastPathComponent().path)
self.init(animation: animation, imageProvider: provider, configuration: configuration)
}
/// Loads a Lottie animation asynchronously from the URL
///
/// - Parameter url: The url to load the animation from.
/// - Parameter imageProvider: An image provider for the animation's image data.
/// If none is supplied Lottie will search in the main bundle for images.
/// - Parameter closure: A closure to be called when the animation has loaded.
public convenience init(
url: URL,
imageProvider: AnimationImageProvider? = nil,
session: URLSession = .shared,
closure: @escaping LottieAnimationView.DownloadClosure,
animationCache: AnimationCacheProvider? = LottieAnimationCache.shared,
configuration: LottieConfiguration = .shared)
{
if let animationCache, let animation = animationCache.animation(forKey: url.absoluteString) {
self.init(animation: animation, imageProvider: imageProvider, configuration: configuration)
closure(nil)
} else {
self.init(animation: nil, imageProvider: imageProvider, configuration: configuration)
LottieAnimation.loadedFrom(url: url, session: session, closure: { animation in
if let animation {
self.animation = animation
closure(nil)
} else {
closure(LottieDownloadError.downloadFailed)
}
}, animationCache: animationCache)
}
}
/// Loads a Lottie animation from a JSON file located in the Asset catalog of the supplied bundle.
/// - Parameter name: The string name of the lottie animation in the asset catalog.
/// - Parameter bundle: The bundle in which the animation is located.
/// Defaults to the Main bundle.
/// - Parameter imageProvider: An image provider for the animation's image data.
/// If none is supplied Lottie will search in the supplied bundle for images.
public convenience init(
asset name: String,
bundle: Bundle = Bundle.main,
imageProvider: AnimationImageProvider? = nil,
animationCache: AnimationCacheProvider? = LottieAnimationCache.shared,
configuration: LottieConfiguration = .shared)
{
let animation = LottieAnimation.asset(name, bundle: bundle, animationCache: animationCache)
let provider = imageProvider ?? BundleImageProvider(bundle: bundle, searchPath: nil)
self.init(animation: animation, imageProvider: provider, configuration: configuration)
}
// MARK: DotLottie
/// Loads a Lottie animation from a .lottie file in the supplied bundle.
///
/// - Parameter dotLottieName: The name of the lottie file without the lottie extension. EG "StarAnimation"
/// - Parameter bundle: The bundle in which the lottie is located. Defaults to `Bundle.main`
/// - Parameter subdirectory: A subdirectory in the bundle in which the lottie is located. Optional.
/// - Parameter animationId: Animation id to play. Optional
/// - Parameter completion: A closure that is called when the .lottie file is finished loading
/// Defaults to first animation in file
public convenience init(
dotLottieName name: String,
bundle: Bundle = Bundle.main,
subdirectory: String? = nil,
animationId: String? = nil,
dotLottieCache: DotLottieCacheProvider? = DotLottieCache.sharedCache,
configuration: LottieConfiguration = .shared,
completion: ((LottieAnimationView, Error?) -> Void)? = nil)
{
self.init(dotLottie: nil, animationId: animationId, configuration: configuration)
DotLottieFile.named(name, bundle: bundle, subdirectory: subdirectory, dotLottieCache: dotLottieCache) { result in
switch result {
case .success(let dotLottieFile):
self.loadAnimation(animationId, from: dotLottieFile)
completion?(self, nil)
case .failure(let error):
completion?(self, error)
}
}
}
/// Loads a Lottie from a .lottie file in a specific path on disk.
///
/// - Parameter dotLottieFilePath: The absolute path of the Lottie file.
/// - Parameter animationId: Animation id to play. Optional
/// - Parameter completion: A closure that is called when the .lottie file is finished loading
/// Defaults to first animation in file
public convenience init(
dotLottieFilePath filePath: String,
animationId: String? = nil,
dotLottieCache: DotLottieCacheProvider? = DotLottieCache.sharedCache,
configuration: LottieConfiguration = .shared,
completion: ((LottieAnimationView, Error?) -> Void)? = nil)
{
self.init(dotLottie: nil, animationId: animationId, configuration: configuration)
DotLottieFile.loadedFrom(filepath: filePath, dotLottieCache: dotLottieCache) { result in
switch result {
case .success(let dotLottieFile):
self.loadAnimation(animationId, from: dotLottieFile)
completion?(self, nil)
case .failure(let error):
completion?(self, error)
}
}
}
/// Loads a Lottie file asynchronously from the URL
///
/// - Parameter dotLottieUrl: The url to load the lottie file from.
/// - Parameter animationId: Animation id to play. Optional. Defaults to first animation in file.
/// - Parameter completion: A closure to be called when the animation has loaded.
public convenience init(
dotLottieUrl url: URL,
animationId: String? = nil,
dotLottieCache: DotLottieCacheProvider? = DotLottieCache.sharedCache,
configuration: LottieConfiguration = .shared,
session: URLSession = .shared,
completion: ((LottieAnimationView, Error?) -> Void)? = nil)
{
if let dotLottieCache, let lottie = dotLottieCache.file(forKey: url.absoluteString) {
self.init(dotLottie: lottie, animationId: animationId, configuration: configuration)
completion?(self, nil)
} else {
self.init(dotLottie: nil, configuration: configuration)
DotLottieFile.loadedFrom(url: url, session: session, dotLottieCache: dotLottieCache) { result in
switch result {
case .success(let lottie):
self.loadAnimation(animationId, from: lottie)
completion?(self, nil)
case .failure(let error):
completion?(self, error)
}
}
}
}
/// Loads a Lottie from a .lottie file located in the Asset catalog of the supplied bundle.
/// - Parameter name: The string name of the lottie file in the asset catalog.
/// - Parameter bundle: The bundle in which the file is located. Defaults to the Main bundle.
/// - Parameter animationId: Animation id to play. Optional
/// - Parameter completion: A closure that is called when the .lottie file is finished loading
/// Defaults to first animation in file
public convenience init(
dotLottieAsset name: String,
bundle: Bundle = Bundle.main,
animationId: String? = nil,
dotLottieCache: DotLottieCacheProvider? = DotLottieCache.sharedCache,
configuration: LottieConfiguration = .shared,
completion: ((LottieAnimationView, Error?) -> Void)? = nil)
{
self.init(dotLottie: nil, animationId: animationId, configuration: configuration)
DotLottieFile.asset(named: name, bundle: bundle, dotLottieCache: dotLottieCache) { result in
switch result {
case .success(let dotLottieFile):
self.loadAnimation(animationId, from: dotLottieFile)
completion?(self, nil)
case .failure(let error):
completion?(self, error)
}
}
}
// MARK: Public
public typealias DownloadClosure = (Error?) -> Void
}
// MARK: - LottieDownloadError
enum LottieDownloadError: Error {
case downloadFailed
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Animation/LottieAnimationViewInitializers.swift
|
Swift
|
unknown
| 9,601
|
// Created by Cal Stephens on 8/3/23.
// Copyright © 2023 Airbnb Inc. All rights reserved.
import Foundation
// MARK: - LottiePlaybackMode
/// Configuration for how a Lottie animation should be played
public enum LottiePlaybackMode: Hashable {
/// The animation is paused at the given state (e.g. paused at a specific frame)
case paused(at: PausedState)
/// The animation is playing using the given playback mode (e.g. looping from the start to the end)
case playing(_ mode: PlaybackMode)
@available(*, deprecated, renamed: "LottiePlaybackMode.paused(at:)", message: "Will be removed in a future major release.")
case progress(_ progress: AnimationProgressTime)
@available(*, deprecated, renamed: "LottiePlaybackMode.paused(at:)", message: "Will be removed in a future major release.")
case frame(_ frame: AnimationFrameTime)
@available(*, deprecated, renamed: "LottiePlaybackMode.paused(at:)", message: "Will be removed in a future major release.")
case time(_ time: TimeInterval)
@available(*, deprecated, renamed: "LottiePlaybackMode.paused(at:)", message: "Will be removed in a future major release.")
case pause
@available(*, deprecated, renamed: "LottiePlaybackMode.playing(_:)", message: "Will be removed in a future major release.")
case fromProgress(_ fromProgress: AnimationProgressTime?, toProgress: AnimationProgressTime, loopMode: LottieLoopMode)
@available(*, deprecated, renamed: "LottiePlaybackMode.playing(_:)", message: "Will be removed in a future major release.")
case fromFrame(_ fromFrame: AnimationFrameTime?, toFrame: AnimationFrameTime, loopMode: LottieLoopMode)
@available(*, deprecated, renamed: "LottiePlaybackMode.playing(_:)", message: "Will be removed in a future major release.")
case fromMarker(
_ fromMarker: String?,
toMarker: String,
playEndMarkerFrame: Bool = true,
loopMode: LottieLoopMode)
@available(*, deprecated, renamed: "LottiePlaybackMode.playing(_:)", message: "Will be removed in a future major release.")
case marker(_ marker: String, loopMode: LottieLoopMode)
@available(*, deprecated, renamed: "LottiePlaybackMode.playing(_:)", message: "Will be removed in a future major release.")
case markers(_ markers: [String])
// MARK: Public
public enum PausedState: Hashable {
/// Any existing animation will be paused at the current frame.
case currentFrame
/// The animation is paused at the given progress value,
/// a value between 0.0 (0% progress) and 1.0 (100% progress).
case progress(_ progress: AnimationProgressTime)
/// The animation is paused at the given frame of the animation.
case frame(_ frame: AnimationFrameTime)
/// The animation is paused at the given time value from the start of the animation.
case time(_ time: TimeInterval)
/// Pauses the animation at a given marker and position
case marker(_ name: String, position: LottieMarkerPosition = .start)
}
public enum PlaybackMode: Hashable {
/// Plays the animation from a progress (0-1) to a progress (0-1).
/// - Parameter fromProgress: The start progress of the animation. If `nil` the animation will start at the current progress.
/// - Parameter toProgress: The end progress of the animation.
/// - Parameter loopMode: The loop behavior of the animation.
case fromProgress(
_ fromProgress: AnimationProgressTime?,
toProgress: AnimationProgressTime,
loopMode: LottieLoopMode)
/// The animation plays from the given `fromFrame` to the given `toFrame`.
/// - Parameter fromFrame: The start frame of the animation. If `nil` the animation will start at the current frame.
/// - Parameter toFrame: The end frame of the animation.
/// - Parameter loopMode: The loop behavior of the animation.
case fromFrame(
_ fromFrame: AnimationFrameTime?,
toFrame: AnimationFrameTime,
loopMode: LottieLoopMode)
/// Plays the animation from a named marker to another marker.
///
/// Markers are point in time that are encoded into the Animation data and assigned a name.
///
/// NOTE: If markers are not found the play command will exit.
///
/// - Parameter fromMarker: The start marker for the animation playback. If `nil` the
/// animation will start at the current progress.
/// - Parameter toMarker: The end marker for the animation playback.
/// - Parameter playEndMarkerFrame: A flag to determine whether or not to play the frame of the end marker. If the
/// end marker represents the end of the section to play, it should be to true. If the provided end marker
/// represents the beginning of the next section, it should be false.
/// - Parameter loopMode: The loop behavior of the animation.
case fromMarker(
_ fromMarker: String?,
toMarker: String,
playEndMarkerFrame: Bool = true,
loopMode: LottieLoopMode)
/// Plays the animation from a named marker to the end of the marker's duration.
///
/// A marker is a point in time with an associated duration that is encoded into the
/// animation data and assigned a name.
///
/// NOTE: If marker is not found the play command will exit.
///
/// - Parameter marker: The start marker for the animation playback.
/// - Parameter loopMode: The loop behavior of the animation.
case marker(
_ marker: String,
loopMode: LottieLoopMode)
/// Plays the given markers sequentially in order.
///
/// A marker is a point in time with an associated duration that is encoded into the
/// animation data and assigned a name. Multiple markers can be played sequentially
/// to create programmable animations.
///
/// If a marker is not found, it will be skipped.
///
/// If a marker doesn't have a duration value, it will play with a duration of 0
/// (effectively being skipped).
///
/// If another animation is played (by calling any `play` method) while this
/// marker sequence is playing, the marker sequence will be cancelled.
///
/// - Parameter markers: The list of markers to play sequentially.
case markers(_ markers: [String])
}
}
extension LottiePlaybackMode {
public static var paused: Self {
.paused(at: .currentFrame)
}
@available(*, deprecated, renamed: "LottiePlaybackMode.playing(_:)", message: "Will be removed in a future major release.")
public static func toProgress(_ toProgress: AnimationProgressTime, loopMode: LottieLoopMode) -> LottiePlaybackMode {
.playing(.fromProgress(nil, toProgress: toProgress, loopMode: loopMode))
}
@available(*, deprecated, renamed: "LottiePlaybackMode.playing(_:)", message: "Will be removed in a future major release.")
public static func toFrame(_ toFrame: AnimationFrameTime, loopMode: LottieLoopMode) -> LottiePlaybackMode {
.playing(.fromFrame(nil, toFrame: toFrame, loopMode: loopMode))
}
@available(*, deprecated, renamed: "LottiePlaybackMode.playing(_:)", message: "Will be removed in a future major release.")
public static func toMarker(
_ toMarker: String,
playEndMarkerFrame: Bool = true,
loopMode: LottieLoopMode)
-> LottiePlaybackMode
{
.playing(.fromMarker(nil, toMarker: toMarker, playEndMarkerFrame: playEndMarkerFrame, loopMode: loopMode))
}
}
extension LottiePlaybackMode.PlaybackMode {
/// Plays the animation from the current progress to a progress value (0-1).
/// - Parameter toProgress: The end progress of the animation.
/// - Parameter loopMode: The loop behavior of the animation.
public static func toProgress(_ toProgress: AnimationProgressTime, loopMode: LottieLoopMode) -> Self {
.fromProgress(nil, toProgress: toProgress, loopMode: loopMode)
}
// Plays the animation from the current frame to the given frame.
/// - Parameter toFrame: The end frame of the animation.
/// - Parameter loopMode: The loop behavior of the animation.
public static func toFrame(_ toFrame: AnimationFrameTime, loopMode: LottieLoopMode) -> Self {
.fromFrame(nil, toFrame: toFrame, loopMode: loopMode)
}
/// Plays the animation from the current frame to some marker.
///
/// Markers are point in time that are encoded into the Animation data and assigned a name.
///
/// NOTE: If the marker isn't found the play command will exit.
///
/// - Parameter toMarker: The end marker for the animation playback.
/// - Parameter playEndMarkerFrame: A flag to determine whether or not to play the frame of the end marker. If the
/// end marker represents the end of the section to play, it should be to true. If the provided end marker
/// represents the beginning of the next section, it should be false.
/// - Parameter loopMode: The loop behavior of the animation.
public static func toMarker(
_ toMarker: String,
playEndMarkerFrame: Bool = true,
loopMode: LottieLoopMode)
-> Self
{
.fromMarker(nil, toMarker: toMarker, playEndMarkerFrame: playEndMarkerFrame, loopMode: loopMode)
}
}
// MARK: - LottieMarkerPosition
/// The position within a marker.
public enum LottieMarkerPosition: Hashable {
case start
case end
}
extension LottiePlaybackMode {
/// Returns a copy of this `PlaybackMode` with the `LottieLoopMode` updated to the given value
func loopMode(_ updatedLoopMode: LottieLoopMode) -> LottiePlaybackMode {
switch self {
case .playing(let playbackMode):
return .playing(playbackMode.loopMode(updatedLoopMode))
case .fromProgress(let fromProgress, toProgress: let toProgress, _):
return .playing(.fromProgress(
fromProgress,
toProgress: toProgress,
loopMode: updatedLoopMode))
case .fromFrame(let fromFrame, toFrame: let toFrame, _):
return .playing(.fromFrame(
fromFrame,
toFrame: toFrame,
loopMode: updatedLoopMode))
case .fromMarker(let fromMarker, let toMarker, let playEndMarkerFrame, _):
return .playing(.fromMarker(
fromMarker,
toMarker: toMarker,
playEndMarkerFrame: playEndMarkerFrame,
loopMode: updatedLoopMode))
case .marker(let marker, _):
return .playing(.marker(marker, loopMode: updatedLoopMode))
case .pause, .paused, .progress(_), .time(_), .frame(_), .markers:
return self
}
}
}
extension LottiePlaybackMode.PlaybackMode {
/// Returns a copy of this `PlaybackMode` with the `LottieLoopMode` updated to the given value
func loopMode(_ updatedLoopMode: LottieLoopMode) -> LottiePlaybackMode.PlaybackMode {
switch self {
case .fromProgress(let fromProgress, let toProgress, _):
return .fromProgress(fromProgress, toProgress: toProgress, loopMode: updatedLoopMode)
case .fromFrame(let fromFrame, let toFrame, _):
return .fromFrame(fromFrame, toFrame: toFrame, loopMode: updatedLoopMode)
case .fromMarker(let fromMarker, let toMarker, let playEndMarkerFrame, _):
return .fromMarker(fromMarker, toMarker: toMarker, playEndMarkerFrame: playEndMarkerFrame, loopMode: updatedLoopMode)
case .marker(let marker, _):
return .marker(marker, loopMode: updatedLoopMode)
case .markers:
return self
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Animation/LottiePlaybackMode.swift
|
Swift
|
unknown
| 11,188
|
// Created by Bryn Bodayle on 1/20/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
#if canImport(SwiftUI)
import SwiftUI
// MARK: - LottieView
/// A wrapper which exposes Lottie's `LottieAnimationView` to SwiftUI
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
public struct LottieView<Placeholder: View>: UIViewConfiguringSwiftUIView {
// MARK: Lifecycle
/// Creates a `LottieView` that displays the given animation
public init(animation: LottieAnimation?) where Placeholder == EmptyView {
_animationSource = State(initialValue: animation.map(LottieAnimationSource.lottieAnimation))
placeholder = nil
}
/// Initializes a `LottieView` with the provided `DotLottieFile` for display.
///
/// - Important: Avoid using this initializer with the `SynchronouslyBlockingCurrentThread` APIs.
/// If decompression of a `.lottie` file is necessary, prefer using the `.init(_ loadAnimation:)`
/// initializer, which takes an asynchronous closure:
/// ```
/// LottieView {
/// try await DotLottieFile.named(name)
/// }
/// ```
public init(dotLottieFile: DotLottieFile?) where Placeholder == EmptyView {
_animationSource = State(initialValue: dotLottieFile.map(LottieAnimationSource.dotLottieFile))
placeholder = nil
}
/// Creates a `LottieView` that asynchronously loads and displays the given `LottieAnimation`.
/// The `loadAnimation` closure is called exactly once in `onAppear`.
/// If you wish to call `loadAnimation` again at a different time, you can use `.reloadAnimationTrigger(...)`.
public init(_ loadAnimation: @escaping () async throws -> LottieAnimation?) where Placeholder == EmptyView {
self.init(loadAnimation, placeholder: EmptyView.init)
}
/// Creates a `LottieView` that asynchronously loads and displays the given `LottieAnimation`.
/// The `loadAnimation` closure is called exactly once in `onAppear`.
/// If you wish to call `loadAnimation` again at a different time, you can use `.reloadAnimationTrigger(...)`.
/// While the animation is loading, the `placeholder` view is shown in place of the `LottieAnimationView`.
public init(
_ loadAnimation: @escaping () async throws -> LottieAnimation?,
@ViewBuilder placeholder: @escaping (() -> Placeholder))
{
self.init {
try await loadAnimation().map(LottieAnimationSource.lottieAnimation)
} placeholder: {
placeholder()
}
}
/// Creates a `LottieView` that asynchronously loads and displays the given `DotLottieFile`.
/// The `loadDotLottieFile` closure is called exactly once in `onAppear`.
/// If you wish to call `loadAnimation` again at a different time, you can use `.reloadAnimationTrigger(...)`.
/// You can use the `DotLottieFile` static methods API which use Swift concurrency to load your `.lottie` files:
/// ```
/// LottieView {
/// try await DotLottieFile.named(name)
/// }
/// ```
public init(_ loadDotLottieFile: @escaping () async throws -> DotLottieFile?) where Placeholder == EmptyView {
self.init(loadDotLottieFile, placeholder: EmptyView.init)
}
/// Creates a `LottieView` that asynchronously loads and displays the given `DotLottieFile`.
/// The `loadDotLottieFile` closure is called exactly once in `onAppear`.
/// If you wish to call `loadAnimation` again at a different time, you can use `.reloadAnimationTrigger(...)`.
/// While the animation is loading, the `placeholder` view is shown in place of the `LottieAnimationView`.
/// You can use the `DotLottieFile` static methods API which use Swift concurrency to load your `.lottie` files:
/// ```
/// LottieView {
/// try await DotLottieFile.named(name)
/// } placeholder: {
/// LoadingView()
/// }
/// ```
public init(
_ loadDotLottieFile: @escaping () async throws -> DotLottieFile?,
@ViewBuilder placeholder: @escaping (() -> Placeholder))
{
self.init {
try await loadDotLottieFile().map(LottieAnimationSource.dotLottieFile)
} placeholder: {
placeholder()
}
}
/// Creates a `LottieView` that asynchronously loads and displays the given `LottieAnimationSource`.
/// The `loadAnimation` closure is called exactly once in `onAppear`.
/// If you wish to call `loadAnimation` again at a different time, you can use `.reloadAnimationTrigger(...)`.
/// While the animation is loading, the `placeholder` view is shown in place of the `LottieAnimationView`.
public init(_ loadAnimation: @escaping () async throws -> LottieAnimationSource?) where Placeholder == EmptyView {
self.init(loadAnimation, placeholder: EmptyView.init)
}
/// Creates a `LottieView` that asynchronously loads and displays the given `LottieAnimationSource`.
/// The `loadAnimation` closure is called exactly once in `onAppear`.
/// If you wish to call `loadAnimation` again at a different time, you can use `.reloadAnimationTrigger(...)`.
/// While the animation is loading, the `placeholder` view is shown in place of the `LottieAnimationView`.
public init(
_ loadAnimation: @escaping () async throws -> LottieAnimationSource?,
@ViewBuilder placeholder: @escaping () -> Placeholder)
{
self.loadAnimation = loadAnimation
self.placeholder = placeholder
_animationSource = State(initialValue: nil)
}
// MARK: Public
public var body: some View {
LottieAnimationView.swiftUIView {
LottieAnimationView(
animationSource: animationSource,
imageProvider: imageProviderConfiguration?.imageProvider,
textProvider: textProvider,
fontProvider: fontProvider,
configuration: configuration,
logger: logger)
}
.sizing(sizing)
.configure { context in
applyCurrentAnimationConfiguration(to: context.view)
}
.configurations(configurations)
.opacity(animationSource == nil ? 0 : 1)
.overlay {
placeholder?()
.opacity(animationSource == nil ? 1 : 0)
}
.onAppear {
loadAnimationIfNecessary()
}
.valueChanged(value: reloadAnimationTrigger) { _ in
reloadAnimationTriggerDidChange()
}
}
/// Returns a copy of this `LottieView` updated to have the given closure applied to its
/// represented `LottieAnimationView` whenever it is updated via the `updateUIView(…)`
/// or `updateNSView(…)` method.
public func configure(_ configure: @escaping (LottieAnimationView) -> Void) -> Self {
var copy = self
copy.configurations.append { context in
configure(context.view)
}
return copy
}
/// Returns a copy of this view that can be resized by scaling its animation to fit the size
/// offered by its parent.
public func resizable() -> Self {
var copy = self
copy.sizing = .proposed
return copy
}
@available(*, deprecated, renamed: "playing()", message: "Will be removed in a future major release.")
public func play() -> Self {
playbackMode(.playing(.fromProgress(nil, toProgress: 1, loopMode: .playOnce)))
}
/// Returns a copy of this view that loops its animation from the start to end whenever visible
public func looping() -> Self {
playbackMode(.playing(.fromProgress(0, toProgress: 1, loopMode: .loop)))
}
@available(*, deprecated, renamed: "playing(_:)", message: "Will be removed in a future major release.")
public func play(loopMode: LottieLoopMode = .playOnce) -> Self {
playbackMode(.playing(.fromProgress(nil, toProgress: 1, loopMode: loopMode)))
}
@available(*, deprecated, renamed: "playbackMode(_:)", message: "Will be removed in a future major release.")
public func play(_ playbackMode: LottiePlaybackMode) -> Self {
self.playbackMode(playbackMode)
}
/// Returns a copy of this view playing with the given playback mode
public func playing(_ mode: LottiePlaybackMode.PlaybackMode) -> Self {
playbackMode(.playing(mode))
}
/// Returns a copy of this view playing from the current frame to the end frame,
/// with the given `LottiePlaybackMode`.
public func playing(loopMode: LottieLoopMode) -> Self {
playbackMode(.playing(.fromProgress(nil, toProgress: 1, loopMode: loopMode)))
}
// Returns a copy of this view playing once from the current frame to the end frame
public func playing() -> Self {
playbackMode(.playing(.fromProgress(nil, toProgress: 1, loopMode: .playOnce)))
}
/// Returns a copy of this view paused with the given state
public func paused(at state: LottiePlaybackMode.PausedState = .currentFrame) -> Self {
playbackMode(.paused(at: state))
}
/// Returns a copy of this view using the given `LottiePlaybackMode`
public func playbackMode(_ playbackMode: LottiePlaybackMode) -> Self {
var copy = self
copy.playbackMode = playbackMode
return copy
}
/// Returns a copy of this view playing its animation at the given speed
public func animationSpeed(_ animationSpeed: Double) -> Self {
var copy = self
copy.animationSpeed = animationSpeed
return copy
}
/// Returns a copy of this view with the given closure that is called whenever the
/// `LottieAnimationSource` provided via `init` is loaded and applied to the underlying `LottieAnimationView`.
public func animationDidLoad(_ animationDidLoad: @escaping (LottieAnimationSource) -> Void) -> Self {
var copy = self
copy.animationDidLoad = animationDidLoad
return copy
}
/// Returns a copy of this view with the given `LottieCompletionBlock` that is called
/// when an animation finishes playing.
public func animationDidFinish(_ animationCompletionHandler: LottieCompletionBlock?) -> Self {
var copy = self
copy.animationCompletionHandler = { [previousCompletionHandler = self.animationCompletionHandler] completed in
previousCompletionHandler?(completed)
animationCompletionHandler?(completed)
}
return copy
}
/// Returns a copy of this view updated to have the provided background behavior.
public func backgroundBehavior(_ value: LottieBackgroundBehavior) -> Self {
configure { view in
view.backgroundBehavior = value
}
}
/// Returns a copy of this view with its accessibility label updated to the given value.
public func accessibilityLabel(_ accessibilityLabel: String?) -> Self {
configure { view in
#if os(macOS)
view.setAccessibilityElement(accessibilityLabel != nil)
view.setAccessibilityLabel(accessibilityLabel)
#else
view.isAccessibilityElement = accessibilityLabel != nil
view.accessibilityLabel = accessibilityLabel
#endif
}
}
/// Returns a copy of this view with its `LottieConfiguration` updated to the given value.
public func configuration(_ configuration: LottieConfiguration) -> Self {
var copy = self
copy.configuration = configuration
copy = copy.configure { view in
if view.configuration != configuration {
view.configuration = configuration
}
}
return copy
}
/// Returns a copy of this view with its `LottieLogger` updated to the given value.
/// - The underlying `LottieAnimationView`'s `LottieLogger` is immutable after configured,
/// so this value is only used when initializing the `LottieAnimationView` for the first time.
public func logger(_ logger: LottieLogger) -> Self {
var copy = self
copy.logger = logger
return copy
}
/// Returns a copy of this view with its image provider updated to the given value.
/// The image provider must be `Equatable` to avoid unnecessary state updates / re-renders.
public func imageProvider<ImageProvider: AnimationImageProvider & Equatable>(_ imageProvider: ImageProvider) -> Self {
var copy = self
copy.imageProviderConfiguration = (
imageProvider: imageProvider,
imageProvidersAreEqual: { untypedLHS, untypedRHS in
guard
let lhs = untypedLHS as? ImageProvider,
let rhs = untypedRHS as? ImageProvider
else { return false }
return lhs == rhs
})
return copy
}
/// Returns a copy of this view with its text provider updated to the given value.
/// The image provider must be `Equatable` to avoid unnecessary state updates / re-renders.
public func textProvider<TextProvider: AnimationKeypathTextProvider & Equatable>(_ textProvider: TextProvider) -> Self {
var copy = self
copy.textProvider = textProvider
copy = copy.configure { view in
if (view.textProvider as? TextProvider) != textProvider {
view.textProvider = textProvider
}
}
return copy
}
/// Returns a copy of this view with its image provider updated to the given value.
/// The image provider must be `Equatable` to avoid unnecessary state updates / re-renders.
public func fontProvider<FontProvider: AnimationFontProvider & Equatable>(_ fontProvider: FontProvider) -> Self {
var copy = self
copy.fontProvider = fontProvider
copy = configure { view in
if (view.fontProvider as? FontProvider) != fontProvider {
view.fontProvider = fontProvider
}
}
return copy
}
/// Returns a copy of this view using the given value provider for the given keypath.
/// The value provider must be `Equatable` to avoid unnecessary state updates / re-renders.
public func valueProvider<ValueProvider: AnyValueProvider & Equatable>(
_ valueProvider: ValueProvider,
for keypath: AnimationKeypath)
-> Self
{
configure { view in
if (view.valueProviders[keypath] as? ValueProvider) != valueProvider {
view.setValueProvider(valueProvider, keypath: keypath)
}
}
}
/// Returns a copy of this view updated to display the given `AnimationProgressTime`.
/// - If the `currentProgress` value is provided, the `currentProgress` of the
/// underlying `LottieAnimationView` is updated. This will pause any existing animations.
/// - If the `animationProgress` is `nil`, no changes will be made and any existing animations
/// will continue playing uninterrupted.
public func currentProgress(_ currentProgress: AnimationProgressTime?) -> Self {
guard let currentProgress else { return self }
var copy = self
copy.playbackMode = .paused(at: .progress(currentProgress))
return copy
}
/// Returns a copy of this view updated to display the given `AnimationFrameTime`.
/// - If the `currentFrame` value is provided, the `currentFrame` of the
/// underlying `LottieAnimationView` is updated. This will pause any existing animations.
/// - If the `currentFrame` is `nil`, no changes will be made and any existing animations
/// will continue playing uninterrupted.
public func currentFrame(_ currentFrame: AnimationFrameTime?) -> Self {
guard let currentFrame else { return self }
var copy = self
copy.playbackMode = .paused(at: .frame(currentFrame))
return copy
}
/// Returns a copy of this view updated to display the given time value.
/// - If the `currentTime` value is provided, the `currentTime` of the
/// underlying `LottieAnimationView` is updated. This will pause any existing animations.
/// - If the `currentTime` is `nil`, no changes will be made and any existing animations
/// will continue playing uninterrupted.
public func currentTime(_ currentTime: TimeInterval?) -> Self {
guard let currentTime else { return self }
var copy = self
copy.playbackMode = .paused(at: .time(currentTime))
return copy
}
/// Returns a new instance of this view, which will invoke the provided `loadAnimation` closure
/// whenever the `binding` value is updated.
///
/// - Note: This function requires a valid `loadAnimation` closure provided during view initialization,
/// otherwise `reloadAnimationTrigger` will have no effect.
/// - Parameters:
/// - binding: The binding that triggers the reloading when its value changes.
/// - showPlaceholder: When `true`, the current animation will be removed before invoking `loadAnimation`,
/// displaying the `Placeholder` until the new animation loads.
/// When `false`, the previous animation remains visible while the new one loads.
public func reloadAnimationTrigger(_ value: some Equatable, showPlaceholder: Bool = true) -> Self {
var copy = self
copy.reloadAnimationTrigger = AnyEquatable(value)
copy.showPlaceholderWhileReloading = showPlaceholder
return copy
}
/// Returns a view that updates the given binding each frame with the animation's `realtimeAnimationProgress`.
/// The `LottieView` is wrapped in a `TimelineView` with the `.animation` schedule.
/// - This is a one-way binding. Its value is updated but never read.
/// - If provided, the binding will be updated each frame with the `realtimeAnimationProgress`
/// of the underlying `LottieAnimationView`. This is potentially expensive since it triggers
/// a state update every frame.
/// - If the binding is `nil`, the `TimelineView` will be paused and no updates will occur to the binding.
@available(iOS 15.0, tvOS 15.0, macOS 12.0, *)
public func getRealtimeAnimationProgress(_ realtimeAnimationProgress: Binding<AnimationProgressTime>?) -> some View {
TimelineView(.animation(paused: realtimeAnimationProgress == nil)) { _ in
configure { view in
if let realtimeAnimationProgress {
DispatchQueue.main.async {
realtimeAnimationProgress.wrappedValue = view.realtimeAnimationProgress
}
}
}
}
}
/// Returns a view that updates the given binding each frame with the animation's `realtimeAnimationProgress`.
/// The `LottieView` is wrapped in a `TimelineView` with the `.animation` schedule.
/// - This is a one-way binding. Its value is updated but never read.
/// - If provided, the binding will be updated each frame with the `realtimeAnimationProgress`
/// of the underlying `LottieAnimationView`. This is potentially expensive since it triggers
/// a state update every frame.
/// - If the binding is `nil`, the `TimelineView` will be paused and no updates will occur to the binding.
@available(iOS 15.0, tvOS 15.0, macOS 12.0, *)
public func getRealtimeAnimationFrame(_ realtimeAnimationFrame: Binding<AnimationFrameTime>?) -> some View {
TimelineView(.animation(paused: realtimeAnimationFrame == nil)) { _ in
configure { view in
if let realtimeAnimationFrame {
DispatchQueue.main.async {
realtimeAnimationFrame.wrappedValue = view.realtimeAnimationFrame
}
}
}
}
}
/// Returns a copy of this view with the `DotLottieConfigurationComponents`
/// updated to the given value.
/// - Defaults to `[.imageProvider]`
/// - If a component is specified here, that value in the `DotLottieConfiguration`
/// of an active dotLottie animation will override any value provided via other methods.
public func dotLottieConfigurationComponents(
_ dotLottieConfigurationComponents: DotLottieConfigurationComponents)
-> Self
{
var copy = self
copy.dotLottieConfigurationComponents = dotLottieConfigurationComponents
return copy
}
// MARK: Internal
var configurations = [SwiftUIView<LottieAnimationView, Void>.Configuration]()
// MARK: Private
@State private var animationSource: LottieAnimationSource?
private var playbackMode: LottiePlaybackMode?
private var animationSpeed: Double?
private var reloadAnimationTrigger: AnyEquatable?
private var loadAnimation: (() async throws -> LottieAnimationSource?)?
private var animationDidLoad: ((LottieAnimationSource) -> Void)?
private var animationCompletionHandler: LottieCompletionBlock?
private var showPlaceholderWhileReloading = false
private var textProvider: AnimationKeypathTextProvider = DefaultTextProvider()
private var fontProvider: AnimationFontProvider = DefaultFontProvider()
private var configuration: LottieConfiguration = .shared
private var dotLottieConfigurationComponents: DotLottieConfigurationComponents = .imageProvider
private var logger: LottieLogger = .shared
private var sizing = SwiftUIMeasurementContainerStrategy.automatic
private let placeholder: (() -> Placeholder)?
private var imageProviderConfiguration: (
imageProvider: AnimationImageProvider,
imageProvidersAreEqual: (AnimationImageProvider, AnimationImageProvider) -> Bool)?
private func loadAnimationIfNecessary() {
guard let loadAnimation else { return }
Task {
do {
animationSource = try await loadAnimation()
} catch {
logger.warn("Failed to load asynchronous Lottie animation with error: \(error)")
}
}
}
private func reloadAnimationTriggerDidChange() {
guard loadAnimation != nil else { return }
if showPlaceholderWhileReloading {
animationSource = nil
}
loadAnimationIfNecessary()
}
/// Applies playback configuration for the current animation to the `LottieAnimationView`
private func applyCurrentAnimationConfiguration(to view: LottieAnimationView) {
guard let animationSource else { return }
var imageProviderConfiguration = imageProviderConfiguration
var playbackMode = playbackMode
var animationSpeed = animationSpeed
// When playing a dotLottie animation, its `DotLottieConfiguration`
// can override some behavior of the animation.
if let dotLottieConfiguration = animationSource.dotLottieAnimation?.configuration {
// Only use the value from the `DotLottieConfiguration` is that component
// is specified in the list of `dotLottieConfigurationComponents`.
if dotLottieConfigurationComponents.contains(.loopMode) {
playbackMode = playbackMode?.loopMode(dotLottieConfiguration.loopMode)
}
if dotLottieConfigurationComponents.contains(.animationSpeed) {
animationSpeed = dotLottieConfiguration.speed
}
if
dotLottieConfigurationComponents.contains(.imageProvider),
let dotLottieImageProvider = dotLottieConfiguration.dotLottieImageProvider
{
imageProviderConfiguration = (
imageProvider: dotLottieImageProvider,
imageProvidersAreEqual: { untypedLHS, untypedRHS in
guard
let lhs = untypedLHS as? DotLottieImageProvider,
let rhs = untypedRHS as? DotLottieImageProvider
else { return false }
return lhs == rhs
})
}
}
// We check referential equality of the animation before updating as updating the
// animation has a side-effect of rebuilding the animation layer, and it would be
// prohibitive to do so on every state update.
if animationSource.animation !== view.animation {
view.loadAnimation(animationSource)
animationDidLoad?(animationSource)
}
if
let playbackMode,
playbackMode != view.currentPlaybackMode
{
view.setPlaybackMode(playbackMode, completion: animationCompletionHandler)
}
if
let (imageProvider, imageProvidersAreEqual) = imageProviderConfiguration,
!imageProvidersAreEqual(imageProvider, view.imageProvider)
{
view.imageProvider = imageProvider
}
if
let animationSpeed,
animationSpeed != view.animationSpeed
{
view.animationSpeed = animationSpeed
}
}
}
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
extension View {
/// The `.overlay` modifier that uses a `ViewBuilder` is available in iOS 15+, this helper function helps us to use the same API in older OSs
fileprivate func overlay(
@ViewBuilder content: () -> some View)
-> some View
{
overlay(content(), alignment: .center)
}
}
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Animation/LottieView.swift
|
Swift
|
unknown
| 23,684
|
//
// AnimationCacheProvider.swift
// lottie-swift
//
// Created by Brandon Withrow on 2/5/19.
//
/// `AnimationCacheProvider` is a protocol that describes an Animation Cache.
/// Animation Cache is used when loading `LottieAnimation` models. Using an Animation Cache
/// can increase performance when loading an animation multiple times.
///
/// Lottie comes with a prebuilt LRU Animation Cache.
public protocol AnimationCacheProvider: AnyObject, Sendable {
func animation(forKey: String) -> LottieAnimation?
func setAnimation(_ animation: LottieAnimation, forKey: String)
func clearCache()
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/AnimationCache/AnimationCacheProvider.swift
|
Swift
|
unknown
| 608
|
//
// DefaultAnimationCache.swift
// Lottie
//
// Created by Marcelo Fabri on 10/18/22.
//
import Foundation
// MARK: - DefaultAnimationCache
/// A thread-safe Animation Cache that will store animations up to `cacheSize`.
///
/// Once `cacheSize` is reached, animations can be ejected.
/// The default size of the cache is 100.
///
/// This cache implementation also responds to memory pressure.
public class DefaultAnimationCache: AnimationCacheProvider {
// MARK: Lifecycle
public init() {
cache.countLimit = Self.defaultCacheCountLimit
}
// MARK: Public
/// The global shared Cache.
public static let sharedCache = DefaultAnimationCache()
/// The maximum number of animations that can be stored in the cache.
public var cacheSize: Int {
get { cache.countLimit }
set { cache.countLimit = newValue }
}
/// Clears the Cache.
public func clearCache() {
cache.removeAllValues()
}
public func animation(forKey key: String) -> LottieAnimation? {
cache.value(forKey: key)
}
public func setAnimation(_ animation: LottieAnimation, forKey key: String) {
cache.setValue(animation, forKey: key)
}
// MARK: Private
private static let defaultCacheCountLimit = 100
/// The underlying storage of this cache.
/// - We use the `LRUCache` library instead of `NSCache`, because `NSCache`
/// clears all cached values when the app is backgrounded instead of
/// only when the app receives a memory warning notification.
private let cache = LRUCache<String, LottieAnimation>()
}
// MARK: Sendable
// LottieAnimationCache has a Sendable requirement, but we can't
// redesign DefaultAnimationCache to be properly Sendable without
// making breaking changes.
// swiftlint:disable:next no_unchecked_sendable
extension DefaultAnimationCache: @unchecked Sendable { }
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/AnimationCache/DefaultAnimationCache.swift
|
Swift
|
unknown
| 1,837
|
//
// LRUAnimationCache.swift
// lottie-swift
//
// Created by Brandon Withrow on 2/5/19.
//
@available(*, deprecated, message: """
Use DefaultAnimationCache instead, which is thread-safe and automatically responds to memory pressure.
""")
public typealias LRUAnimationCache = DefaultAnimationCache
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/AnimationCache/LRUAnimationCache.swift
|
Swift
|
unknown
| 307
|
//
// LottieAnimationCache.swift
// Lottie
//
// Created by Marcelo Fabri on 10/17/22.
//
/// A customization point to configure which `AnimationCacheProvider` will be used.
public enum LottieAnimationCache {
/// The animation cache that will be used when loading `LottieAnimation` models.
/// Using an Animation Cache can increase performance when loading an animation multiple times.
/// Defaults to DefaultAnimationCache.sharedCache.
public static var shared: AnimationCacheProvider? = DefaultAnimationCache.sharedCache
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/AnimationCache/LottieAnimationCache.swift
|
Swift
|
unknown
| 538
|
// Created by Cal Stephens on 7/14/23.
// Copyright © 2023 Airbnb Inc. All rights reserved.
/// How animation files should be decoded
public enum DecodingStrategy: Hashable {
/// Use Codable. This is was the default strategy introduced on Lottie 3, but should be rarely
/// used as it's slower than `dictionaryBased`. Kept here for any possible compatibility issues
/// that may come up, but consider it soft-deprecated.
case legacyCodable
/// Manually deserialize a dictionary into an Animation.
/// This should be at least 2-3x faster than using Codable and due to that
/// it's the default as of Lottie 4.x.
case dictionaryBased
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Configuration/DecodingStrategy.swift
|
Swift
|
unknown
| 653
|
// Created by Cal Stephens on 12/13/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
import QuartzCore
/// Global configuration options for Lottie animations
public struct LottieConfiguration: Hashable {
// MARK: Lifecycle
public init(
renderingEngine: RenderingEngineOption = .automatic,
decodingStrategy: DecodingStrategy = .dictionaryBased,
colorSpace: CGColorSpace = CGColorSpaceCreateDeviceRGB(),
reducedMotionOption: ReducedMotionOption = .systemReducedMotionToggle)
{
self.renderingEngine = renderingEngine
self.decodingStrategy = decodingStrategy
self.colorSpace = colorSpace
self.reducedMotionOption = reducedMotionOption
}
// MARK: Public
/// The global configuration of Lottie,
/// which applies to all `LottieAnimationView`s by default.
public static var shared = LottieConfiguration()
/// The rendering engine implementation to use when displaying an animation
/// - Defaults to `RenderingEngineOption.automatic`, which uses the
/// Core Animation rendering engine for supported animations, and
/// falls back to using the Main Thread rendering engine for
/// animations that use features not supported by the Core Animation engine.
public var renderingEngine: RenderingEngineOption
/// The decoding implementation to use when parsing an animation JSON file
public var decodingStrategy: DecodingStrategy
/// Options for controlling animation behavior in response to user / system "reduced motion" configuration.
/// - Defaults to `ReducedMotionOption.systemReducedMotionToggle`, which returns `.reducedMotion`
/// when the system `UIAccessibility.isReduceMotionEnabled` option is `true`.
public var reducedMotionOption: ReducedMotionOption
/// The color space to be used for rendering
/// - Defaults to `CGColorSpaceCreateDeviceRGB()`
public var colorSpace: CGColorSpace
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Configuration/LottieConfiguration.swift
|
Swift
|
unknown
| 1,898
|
// Created by Cal Stephens on 7/14/23.
// Copyright © 2023 Airbnb Inc. All rights reserved.
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif
// MARK: - ReducedMotionOption
/// Options for controlling animation behavior in response to user / system "reduced motion" configuration
public enum ReducedMotionOption {
/// Always use the specific given `ReducedMotionMode` value.
case specific(ReducedMotionMode)
/// Dynamically check the given `ReducedMotionOptionProvider` each time an animation begins.
/// - Includes a Hashable `dataID` to support `ReducedMotionOption`'s `Hashable` requirement,
/// which is required due to `LottieConfiguration`'s existing `Hashable` requirement.
case dynamic(ReducedMotionOptionProvider, dataID: AnyHashable)
}
extension ReducedMotionOption {
/// The standard behavior where Lottie animations play normally with no overrides.
/// By default this mode is used when the system "reduced motion" option is disabled.
public static var standardMotion: ReducedMotionOption { .specific(.standardMotion) }
/// Lottie animations with a "reduced motion" marker will play that marker instead of any other animations.
/// By default this mode is used when the system "reduced motion" option is enabled.
/// - Valid marker names include "reduced motion", "reducedMotion", "reduced_motion" (case insensitive).
public static var reducedMotion: ReducedMotionOption { .specific(.reducedMotion) }
/// A `ReducedMotionOptionProvider` that returns `.reducedMotion` when
/// the system `UIAccessibility.isReduceMotionEnabled` option is `true`.
/// This is the default option of `LottieConfiguration`.
public static var systemReducedMotionToggle: ReducedMotionOption {
.dynamic(SystemReducedMotionOptionProvider(), dataID: ObjectIdentifier(SystemReducedMotionOptionProvider.self))
}
}
extension ReducedMotionOption {
/// The current `ReducedMotionMode` based on the currently selected option.
public var currentReducedMotionMode: ReducedMotionMode {
switch self {
case .specific(let specificMode):
return specificMode
case .dynamic(let optionProvider, _):
return optionProvider.currentReducedMotionMode
}
}
}
// MARK: Hashable
extension ReducedMotionOption: Hashable {
public static func ==(_ lhs: ReducedMotionOption, _ rhs: ReducedMotionOption) -> Bool {
switch (lhs, rhs) {
case (.specific(let lhsMode), .specific(let rhsMode)):
return lhsMode == rhsMode
case (.dynamic(_, let lhsDataID), .dynamic(_, dataID: let rhsDataID)):
return lhsDataID == rhsDataID
case (.dynamic, .specific), (.specific, .dynamic):
return false
}
}
public func hash(into hasher: inout Hasher) {
switch self {
case .specific(let mode):
hasher.combine(mode)
case .dynamic(_, let dataID):
hasher.combine(dataID)
}
}
}
// MARK: - ReducedMotionMode
public enum ReducedMotionMode: Hashable {
/// The default behavior where Lottie animations play normally with no overrides
/// By default this mode is used when the system "reduced motion" option is disabled.
case standardMotion
/// Lottie animations with a "reduced motion" marker will play that marker instead of any other animations.
/// By default this mode is used when the system "reduced motion" option is enabled.
case reducedMotion
}
// MARK: - ReducedMotionOptionProvider
/// A type that returns a dynamic `ReducedMotionMode` which is checked when playing a Lottie animation.
public protocol ReducedMotionOptionProvider {
var currentReducedMotionMode: ReducedMotionMode { get }
}
// MARK: - SystemReducedMotionOptionProvider
/// A `ReducedMotionOptionProvider` that returns `.reducedMotion` when
/// the system `UIAccessibility.isReduceMotionEnabled` option is `true`.
public struct SystemReducedMotionOptionProvider: ReducedMotionOptionProvider {
public init() { }
public var currentReducedMotionMode: ReducedMotionMode {
#if canImport(UIKit)
if UIAccessibility.isReduceMotionEnabled {
return .reducedMotion
} else {
return .standardMotion
}
#else
return .standardMotion
#endif
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Configuration/ReducedMotionOption.swift
|
Swift
|
unknown
| 4,191
|
// Created by Cal Stephens on 7/14/23.
// Copyright © 2023 Airbnb Inc. All rights reserved.
// MARK: - RenderingEngineOption
public enum RenderingEngineOption: Hashable {
/// Uses the Core Animation engine for supported animations, and falls back to using
/// the Main Thread engine for animations that use features not supported by the
/// Core Animation engine.
case automatic
/// Uses the specified rendering engine
case specific(RenderingEngine)
// MARK: Public
/// The Main Thread rendering engine, which supports all Lottie features
/// but runs on the main thread, which comes with some CPU overhead and
/// can cause the animation to play at a low framerate when the CPU is busy.
public static var mainThread: RenderingEngineOption { .specific(.mainThread) }
/// The Core Animation rendering engine, that animates using Core Animation
/// and has better performance characteristics than the Main Thread engine,
/// but doesn't support all Lottie features.
/// - In general, prefer using `RenderingEngineOption.automatic` over
/// `RenderingEngineOption.coreAnimation`. The Core Animation rendering
/// engine doesn't support all features supported by the Main Thread
/// rendering engine. When using `RenderingEngineOption.automatic`,
/// Lottie will automatically fall back to the Main Thread engine
/// when necessary.
public static var coreAnimation: RenderingEngineOption { .specific(.coreAnimation) }
}
// MARK: - RenderingEngine
/// The rendering engine implementation to use when displaying an animation
public enum RenderingEngine: Hashable {
/// The Main Thread rendering engine, which supports all Lottie features
/// but runs on the main thread, which comes with some CPU overhead and
/// can cause the animation to play at a low framerate when the CPU is busy.
case mainThread
/// The Core Animation rendering engine, that animates using Core Animation
/// and has better performance characteristics than the Main Thread engine,
/// but doesn't support all Lottie features.
case coreAnimation
}
// MARK: - RenderingEngineOption + RawRepresentable, CustomStringConvertible
extension RenderingEngineOption: RawRepresentable, CustomStringConvertible {
// MARK: Lifecycle
public init?(rawValue: String) {
if rawValue == "Automatic" {
self = .automatic
} else if let engine = RenderingEngine(rawValue: rawValue) {
self = .specific(engine)
} else {
return nil
}
}
// MARK: Public
public var rawValue: String {
switch self {
case .automatic:
return "Automatic"
case .specific(let engine):
return engine.rawValue
}
}
public var description: String {
rawValue
}
}
// MARK: - RenderingEngine + RawRepresentable, CustomStringConvertible
extension RenderingEngine: RawRepresentable, CustomStringConvertible {
// MARK: Lifecycle
public init?(rawValue: String) {
switch rawValue {
case "Main Thread":
self = .mainThread
case "Core Animation":
self = .coreAnimation
default:
return nil
}
}
// MARK: Public
public var rawValue: String {
switch self {
case .mainThread:
return "Main Thread"
case .coreAnimation:
return "Core Animation"
}
}
public var description: String {
rawValue
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Configuration/RenderingEngineOption.swift
|
Swift
|
unknown
| 3,356
|
//
// AnimatedButton.swift
// lottie-swift
//
// Created by Brandon Withrow on 2/4/19.
//
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif
// MARK: - AnimatedButton
/// An interactive button that plays an animation when pressed.
open class AnimatedButton: AnimatedControl {
// MARK: Lifecycle
public override init(
animation: LottieAnimation?,
configuration: LottieConfiguration = .shared)
{
super.init(animation: animation, configuration: configuration)
#if canImport(UIKit)
isAccessibilityElement = true
#elseif canImport(AppKit)
setAccessibilityElement(true)
#endif
}
public override init() {
super.init()
#if canImport(UIKit)
isAccessibilityElement = true
#elseif canImport(AppKit)
setAccessibilityElement(true)
#endif
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
#if canImport(UIKit)
isAccessibilityElement = true
#elseif canImport(AppKit)
setAccessibilityElement(true)
#endif
}
// MARK: Open
#if canImport(UIKit)
open override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
let _ = super.beginTracking(touch, with: event)
let touchEvent = UIControl.Event.touchDown
if let playRange = rangesForEvents[touchEvent.id] {
animationView.play(fromProgress: playRange.from, toProgress: playRange.to, loopMode: .playOnce)
}
return true
}
open override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
super.endTracking(touch, with: event)
let touchEvent: UIControl.Event
if let touch, bounds.contains(touch.location(in: self)) {
touchEvent = UIControl.Event.touchUpInside
performAction?()
} else {
touchEvent = UIControl.Event.touchUpOutside
}
if let playRange = rangesForEvents[touchEvent.id] {
animationView.play(fromProgress: playRange.from, toProgress: playRange.to, loopMode: .playOnce)
}
}
#elseif canImport(AppKit)
open override func handle(_ event: LottieNSControlEvent) {
super.handle(event)
if let playRange = rangesForEvents[event.id] {
animationView.play(fromProgress: playRange.from, toProgress: playRange.to, loopMode: .playOnce)
}
if event == .touchUpInside {
performAction?()
}
}
#endif
// MARK: Public
/// A closure that is called when the button is pressed / clicked
public var performAction: (() -> Void)?
#if canImport(UIKit)
public override var accessibilityTraits: UIAccessibilityTraits {
set { super.accessibilityTraits = newValue }
get { super.accessibilityTraits.union(.button) }
}
#endif
/// Sets the play range for the given UIControlEvent.
public func setPlayRange(fromProgress: AnimationProgressTime, toProgress: AnimationProgressTime, event: LottieControlEvent) {
rangesForEvents[event.id] = (from: fromProgress, to: toProgress)
}
/// Sets the play range for the given UIControlEvent.
public func setPlayRange(fromMarker fromName: String, toMarker toName: String, event: LottieControlEvent) {
if
let start = animationView.progressTime(forMarker: fromName),
let end = animationView.progressTime(forMarker: toName)
{
rangesForEvents[event.id] = (from: start, to: end)
}
}
// MARK: Private
private var rangesForEvents: [AnyHashable: (from: CGFloat, to: CGFloat)] = [LottieControlEvent.touchUpInside.id: (
from: 0,
to: 1)]
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Controls/AnimatedButton.swift
|
Swift
|
unknown
| 3,480
|
//
// AnimatedControl.swift
// lottie-swift
//
// Created by Brandon Withrow on 2/4/19.
//
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif
// MARK: - AnimatedControl
/// Lottie comes prepacked with a two Animated Controls, `AnimatedSwitch` and
/// `AnimatedButton`. Both of these controls are built on top of `AnimatedControl`
///
/// `AnimatedControl` is a subclass of `UIControl` that provides an interactive
/// mechanism for controlling the visual state of an animation in response to
/// user actions.
///
/// The `AnimatedControl` will show and hide layers depending on the current
/// `UIControl.State` of the control.
///
/// Users of `AnimationControl` can set a Layer Name for each `UIControl.State`.
/// When the state is change the `AnimationControl` will change the visibility
/// of its layers.
///
/// NOTE: Do not initialize directly. This is intended to be subclassed.
open class AnimatedControl: LottieControlType {
// MARK: Lifecycle
// MARK: Initializers
public init(
animation: LottieAnimation?,
configuration: LottieConfiguration = .shared)
{
animationView = LottieAnimationView(
animation: animation,
configuration: configuration)
super.init(frame: animation?.bounds ?? .zero)
commonInit()
}
public init() {
animationView = LottieAnimationView()
super.init(frame: .zero)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
animationView = LottieAnimationView()
super.init(coder: aDecoder)
commonInit()
}
// MARK: Open
// MARK: UIControl Overrides
open override var isEnabled: Bool {
didSet {
updateForState()
}
}
#if canImport(UIKit)
open override var isSelected: Bool {
didSet {
updateForState()
}
}
#endif
open override var isHighlighted: Bool {
didSet {
updateForState()
}
}
open override var intrinsicContentSize: CGSize {
animationView.intrinsicContentSize
}
#if canImport(UIKit)
open override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
updateForState()
return super.beginTracking(touch, with: event)
}
open override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
updateForState()
return super.continueTracking(touch, with: event)
}
open override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
updateForState()
return super.endTracking(touch, with: event)
}
open override func cancelTracking(with event: UIEvent?) {
updateForState()
super.cancelTracking(with: event)
}
#elseif canImport(AppKit)
open override func mouseDown(with mouseDownEvent: NSEvent) {
guard let window else { return }
currentState = .highlighted
updateForState()
handle(LottieControlEvent(mouseDownEvent.type, inside: eventIsInside(mouseDownEvent)))
// AppKit mouse-tracking loop from:
// https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/EventOverview/HandlingMouseEvents/HandlingMouseEvents.html#//apple_ref/doc/uid/10000060i-CH6-SW4
var keepOn = true
while
keepOn,
let event = window.nextEvent(
matching: .any,
until: .distantFuture,
inMode: .eventTracking,
dequeue: true)
{
if event.type == .leftMouseUp {
keepOn = false
}
let isInside = eventIsInside(event)
handle(LottieControlEvent(event.type, inside: isInside))
let expectedState = (isInside && keepOn) ? LottieNSControlState.highlighted : .normal
if currentState != expectedState {
currentState = expectedState
updateForState()
}
}
}
func handle(_: LottieNSControlEvent) {
// To be overridden in subclasses
}
private func eventIsInside(_ event: NSEvent) -> Bool {
let mouseLocation = convert(event.locationInWindow, from: nil)
return isMousePoint(mouseLocation, in: bounds)
}
#endif
open func animationDidSet() { }
// MARK: Public
/// The animation view in which the animation is rendered.
public let animationView: LottieAnimationView
/// The animation backing the animated control.
public var animation: LottieAnimation? {
didSet {
animationView.animation = animation
animationView.bounds = animation?.bounds ?? .zero
#if canImport(UIKit)
setNeedsLayout()
#elseif canImport(AppKit)
needsLayout = true
#endif
updateForState()
animationDidSet()
}
}
/// The speed of the animation playback. Defaults to 1
public var animationSpeed: CGFloat {
set { animationView.animationSpeed = newValue }
get { animationView.animationSpeed }
}
/// Sets which Animation Layer should be visible for the given state.
public func setLayer(named: String, forState: LottieControlState) {
stateMap[forState.rawValue] = named
updateForState()
}
/// Sets a ValueProvider for the specified keypath
public func setValueProvider(_ valueProvider: AnyValueProvider, keypath: AnimationKeypath) {
animationView.setValueProvider(valueProvider, keypath: keypath)
}
// MARK: Internal
var stateMap: [UInt: String] = [:]
#if canImport(UIKit)
var currentState: LottieControlState {
state
}
#elseif canImport(AppKit)
var currentState = LottieControlState.normal
#endif
func updateForState() {
guard let animationLayer = animationView.animationLayer else { return }
if
let layerName = stateMap[currentState.rawValue],
let stateLayer = animationLayer.layer(for: AnimationKeypath(keypath: layerName))
{
for layer in animationLayer._animationLayers {
layer.isHidden = true
}
stateLayer.isHidden = false
} else {
for layer in animationLayer._animationLayers {
layer.isHidden = false
}
}
}
// MARK: Private
private func commonInit() {
#if canImport(UIKit)
animationView.clipsToBounds = false
clipsToBounds = true
#endif
animationView.translatesAutoresizingMaskIntoConstraints = false
animationView.backgroundBehavior = .forceFinish
addSubview(animationView)
animationView.contentMode = .scaleAspectFit
#if canImport(UIKit)
animationView.isUserInteractionEnabled = false
#endif
animationView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
animationView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
animationView.topAnchor.constraint(equalTo: topAnchor).isActive = true
animationView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Controls/AnimatedControl.swift
|
Swift
|
unknown
| 6,636
|
//
// AnimatedSwitch.swift
// lottie-swift
//
// Created by Brandon Withrow on 2/4/19.
//
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif
// MARK: - AnimatedSwitch
/// An interactive switch with an 'On' and 'Off' state. When the user taps on the
/// switch the state is toggled and the appropriate animation is played.
///
/// Both the 'On' and 'Off' have an animation play range associated with their state.
///
/// Also available as a SwiftUI view (`LottieSwitch`).
open class AnimatedSwitch: AnimatedControl {
// MARK: Lifecycle
public override init(
animation: LottieAnimation?,
configuration: LottieConfiguration = .shared)
{
/// Generate a haptic generator if available.
#if os(iOS)
hapticGenerator = HapticGenerator()
#else
hapticGenerator = NullHapticGenerator()
#endif
super.init(animation: animation, configuration: configuration)
#if canImport(UIKit)
isAccessibilityElement = true
#elseif canImport(AppKit)
setAccessibilityElement(true)
#endif
updateOnState(isOn: _isOn, animated: false, shouldFireHaptics: false)
}
public override init() {
/// Generate a haptic generator if available.
#if os(iOS)
hapticGenerator = HapticGenerator()
#else
hapticGenerator = NullHapticGenerator()
#endif
super.init()
#if canImport(UIKit)
isAccessibilityElement = true
#elseif canImport(AppKit)
setAccessibilityElement(true)
#endif
updateOnState(isOn: _isOn, animated: false, shouldFireHaptics: false)
}
required public init?(coder aDecoder: NSCoder) {
/// Generate a haptic generator if available.
#if os(iOS)
hapticGenerator = HapticGenerator()
#else
hapticGenerator = NullHapticGenerator()
#endif
super.init(coder: aDecoder)
#if canImport(UIKit)
isAccessibilityElement = true
#elseif canImport(AppKit)
setAccessibilityElement(true)
#endif
}
// MARK: Open
open override func animationDidSet() {
updateOnState(isOn: _isOn, animated: animateUpdateWhenChangingAnimation, shouldFireHaptics: false)
}
#if canImport(UIKit)
open override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
super.endTracking(touch, with: event)
updateOnState(isOn: !_isOn, animated: true, shouldFireHaptics: true)
sendActions(for: .valueChanged)
}
#elseif canImport(AppKit)
open override func handle(_ event: LottieNSControlEvent) {
super.handle(event)
if event == .touchUpInside {
updateOnState(isOn: !_isOn, animated: true, shouldFireHaptics: true)
}
}
#endif
// MARK: Public
/// Defines what happens when the user taps the switch while an
/// animation is still in flight
public enum CancelBehavior {
case reverse // default - plays the current animation in reverse
case none // does not update the animation when canceled
}
/// The cancel behavior for the switch. See CancelBehavior for options
public var cancelBehavior: CancelBehavior = .reverse
/// If `false` the switch will not play the animation when changing between animations.
public var animateUpdateWhenChangingAnimation = true
#if canImport(UIKit)
public override var accessibilityTraits: UIAccessibilityTraits {
set { super.accessibilityTraits = newValue }
get { super.accessibilityTraits.union(.button) }
}
#endif
/// A closure that is called when the `isOn` state is updated
public var stateUpdated: ((_ isOn: Bool) -> Void)?
/// The current state of the switch.
public var isOn: Bool {
set {
/// This is forwarded to a private variable because the animation needs to be updated without animation when set externally and with animation when set internally.
guard _isOn != newValue else { return }
updateOnState(isOn: newValue, animated: false, shouldFireHaptics: false)
}
get {
_isOn
}
}
/// Set the state of the switch and specify animation and haptics
public func setIsOn(_ isOn: Bool, animated: Bool, shouldFireHaptics: Bool = true) {
guard isOn != _isOn else { return }
updateOnState(isOn: isOn, animated: animated, shouldFireHaptics: shouldFireHaptics)
}
/// Sets the play range for the given state. When the switch is toggled, the animation range is played.
public func setProgressForState(
fromProgress: AnimationProgressTime,
toProgress: AnimationProgressTime,
forOnState: Bool)
{
if forOnState {
onStartProgress = fromProgress
onEndProgress = toProgress
} else {
offStartProgress = fromProgress
offEndProgress = toProgress
}
updateOnState(isOn: _isOn, animated: false, shouldFireHaptics: false)
}
// MARK: Internal
private(set) var onStartProgress: CGFloat = 0
private(set) var onEndProgress: CGFloat = 1
private(set) var offStartProgress: CGFloat = 1
private(set) var offEndProgress: CGFloat = 0
// MARK: Animation State
func updateOnState(isOn: Bool, animated: Bool, shouldFireHaptics: Bool) {
_isOn = isOn
var startProgress = isOn ? onStartProgress : offStartProgress
var endProgress = isOn ? onEndProgress : offEndProgress
let finalProgress = endProgress
if cancelBehavior == .reverse {
let realtimeProgress = animationView.realtimeAnimationProgress
let previousStateStart = isOn ? offStartProgress : onStartProgress
let previousStateEnd = isOn ? offEndProgress : onEndProgress
if
realtimeProgress.isInRange(
min(previousStateStart, previousStateEnd),
max(previousStateStart, previousStateEnd))
{
/// Animation is currently in the previous time range. Reverse the previous play.
startProgress = previousStateEnd
endProgress = previousStateStart
}
}
updateAccessibilityLabel()
guard animated == true else {
animationView.currentProgress = finalProgress
return
}
if shouldFireHaptics {
hapticGenerator.generateImpact()
}
animationView.play(
fromProgress: startProgress,
toProgress: endProgress,
loopMode: LottieLoopMode.playOnce,
completion: { [weak self] finished in
guard let self else { return }
// For the Main Thread rendering engine, we freeze the animation at the expected final progress
// once the animation is complete. This isn't necessary on the Core Animation engine.
if finished, !(self.animationView.animationLayer is CoreAnimationLayer) {
self.animationView.currentProgress = finalProgress
}
})
}
// MARK: Fileprivate
fileprivate var hapticGenerator: ImpactGenerator
fileprivate var _isOn = false {
didSet {
stateUpdated?(_isOn)
}
}
// MARK: Private
private func updateAccessibilityLabel() {
let value = _isOn ? NSLocalizedString("On", comment: "On") : NSLocalizedString("Off", comment: "Off")
#if canImport(UIKit)
accessibilityValue = value
#elseif canImport(AppKit)
setAccessibilityValue(value)
#endif
}
}
// MARK: - ImpactGenerator
protocol ImpactGenerator {
func generateImpact()
}
#if os(iOS)
class HapticGenerator: ImpactGenerator {
// MARK: Internal
func generateImpact() {
impact.impactOccurred()
}
// MARK: Fileprivate
fileprivate let impact = UIImpactFeedbackGenerator(style: .light)
}
#else
// MARK: - NullHapticGenerator
class NullHapticGenerator: ImpactGenerator {
func generateImpact() { }
}
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Controls/AnimatedSwitch.swift
|
Swift
|
unknown
| 7,495
|
// Created by Cal Stephens on 8/14/23.
// Copyright © 2023 Airbnb Inc. All rights reserved.
#if canImport(SwiftUI)
import SwiftUI
/// A wrapper which exposes Lottie's `AnimatedButton` to SwiftUI
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
public struct LottieButton: UIViewConfiguringSwiftUIView {
// MARK: Lifecycle
public init(animation: LottieAnimation?, action: @escaping () -> Void) {
self.animation = animation
self.action = action
}
// MARK: Public
public var body: some View {
AnimatedButton.swiftUIView {
let button = AnimatedButton(animation: animation, configuration: configuration)
button.performAction = action
return button
}
.configure { context in
// We check referential equality of the animation before updating as updating the
// animation has a side-effect of rebuilding the animation layer, and it would be
// prohibitive to do so on every state update.
if animation !== context.view.animationView.animation {
context.view.animationView.animation = animation
}
#if os(macOS)
// Disable the intrinsic content size constraint on the inner animation view,
// or the Epoxy `SwiftUIMeasurementContainer` won't size this view correctly.
context.view.animationView.isVerticalContentSizeConstraintActive = false
context.view.animationView.isHorizontalContentSizeConstraintActive = false
#endif
}
.configurations(configurations)
}
/// Returns a copy of this `LottieView` updated to have the given closure applied to its
/// represented `LottieAnimationView` whenever it is updated via the `updateUIView(…)`
/// or `updateNSView(…)` method.
public func configure(_ configure: @escaping (AnimatedButton) -> Void) -> Self {
var copy = self
copy.configurations.append { context in
configure(context.view)
}
return copy
}
/// Returns a copy of this view with its `LottieConfiguration` updated to the given value.
public func configuration(_ configuration: LottieConfiguration) -> Self {
var copy = self
copy.configuration = configuration
copy = copy.configure { view in
if view.animationView.configuration != configuration {
view.animationView.configuration = configuration
}
}
return copy
}
/// Returns a copy of this view configured to animate between the
/// given progress values when the given event is triggered
public func animate(
fromProgress: AnimationProgressTime,
toProgress: AnimationProgressTime,
on event: LottieControlEvent)
-> Self
{
configure { view in
// `setPlayRange` just modifies a dictionary,
// so we can just call it on every state update without diffing
view.setPlayRange(fromProgress: fromProgress, toProgress: toProgress, event: event)
}
}
/// Returns a copy of this view configured to animate between the
/// given markers when the given event is triggered
public func animate(
fromMarker: String,
toMarker: String,
on event: LottieControlEvent)
-> Self
{
configure { view in
// `setPlayRange` just modifies a dictionary,
// so we can just call it on every state update without diffing
view.setPlayRange(fromMarker: fromMarker, toMarker: toMarker, event: event)
}
}
/// Returns a copy of this view using the given value provider for the given keypath.
/// The value provider must be `Equatable` to avoid unnecessary state updates / re-renders.
public func valueProvider<ValueProvider: AnyValueProvider & Equatable>(
_ valueProvider: ValueProvider,
for keypath: AnimationKeypath)
-> Self
{
configure { view in
if (view.animationView.valueProviders[keypath] as? ValueProvider) != valueProvider {
view.animationView.setValueProvider(valueProvider, keypath: keypath)
}
}
}
// MARK: Internal
var configurations = [SwiftUIView<AnimatedButton, Void>.Configuration]()
// MARK: Private
private let animation: LottieAnimation?
private let action: () -> Void
private var configuration: LottieConfiguration = .shared
}
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Controls/LottieButton.swift
|
Swift
|
unknown
| 4,154
|
// Created by Cal Stephens on 8/11/23.
// Copyright © 2023 Airbnb Inc. All rights reserved.
#if canImport(SwiftUI)
import SwiftUI
/// A wrapper which exposes Lottie's `AnimatedSwitch` to SwiftUI
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
public struct LottieSwitch: UIViewConfiguringSwiftUIView {
// MARK: Lifecycle
public init(animation: LottieAnimation?) {
self.animation = animation
}
// MARK: Public
public var body: some View {
AnimatedSwitch.swiftUIView {
let animatedSwitch = AnimatedSwitch(animation: animation, configuration: configuration)
animatedSwitch.isOn = isOn?.wrappedValue ?? false
return animatedSwitch
}
.configure { context in
// We check referential equality of the animation before updating as updating the
// animation has a side-effect of rebuilding the animation layer, and it would be
// prohibitive to do so on every state update.
if animation !== context.view.animationView.animation {
context.view.animationView.animation = animation
}
#if os(macOS)
// Disable the intrinsic content size constraint on the inner animation view,
// or the Epoxy `SwiftUIMeasurementContainer` won't size this view correctly.
context.view.animationView.isVerticalContentSizeConstraintActive = false
context.view.animationView.isHorizontalContentSizeConstraintActive = false
#endif
if let isOn = isOn?.wrappedValue, isOn != context.view.isOn {
context.view.setIsOn(isOn, animated: true)
}
}
.configurations(configurations)
}
/// Returns a copy of this `LottieView` updated to have the given closure applied to its
/// represented `LottieAnimationView` whenever it is updated via the `updateUIView(…)`
/// or `updateNSView(…)` method.
public func configure(_ configure: @escaping (AnimatedSwitch) -> Void) -> Self {
var copy = self
copy.configurations.append { context in
configure(context.view)
}
return copy
}
/// Returns a copy of this view with its `LottieConfiguration` updated to the given value.
public func configuration(_ configuration: LottieConfiguration) -> Self {
var copy = self
copy.configuration = configuration
copy = copy.configure { view in
if view.animationView.configuration != configuration {
view.animationView.configuration = configuration
}
}
return copy
}
/// Returns a copy of this view with the given `Binding` reflecting the `isOn` state of the switch.
public func isOn(_ binding: Binding<Bool>) -> Self {
var copy = self
copy.isOn = binding
return copy.configure { view in
view.stateUpdated = { isOn in
DispatchQueue.main.async {
binding.wrappedValue = isOn
}
}
}
}
/// Returns a copy of this view with the "on" animation configured
/// to start and end at the given progress values.
/// Defaults to playing the entire animation forwards (0...1).
public func onAnimation(
fromProgress onStartProgress: AnimationProgressTime,
toProgress onEndProgress: AnimationProgressTime)
-> Self
{
configure { view in
if onStartProgress != view.onStartProgress || onEndProgress != view.onEndProgress {
view.setProgressForState(
fromProgress: onStartProgress,
toProgress: onEndProgress,
forOnState: true)
}
}
}
/// Returns a copy of this view with the "on" animation configured
/// to start and end at the given progress values.
/// Defaults to playing the entire animation backwards (1...0).
public func offAnimation(
fromProgress offStartProgress: AnimationProgressTime,
toProgress offEndProgress: AnimationProgressTime)
-> Self
{
configure { view in
if offStartProgress != view.offStartProgress || offEndProgress != view.offEndProgress {
view.setProgressForState(
fromProgress: offStartProgress,
toProgress: offEndProgress,
forOnState: false)
}
}
}
/// Returns a copy of this view using the given value provider for the given keypath.
/// The value provider must be `Equatable` to avoid unnecessary state updates / re-renders.
public func valueProvider<ValueProvider: AnyValueProvider & Equatable>(
_ valueProvider: ValueProvider,
for keypath: AnimationKeypath)
-> Self
{
configure { view in
if (view.animationView.valueProviders[keypath] as? ValueProvider) != valueProvider {
view.animationView.setValueProvider(valueProvider, keypath: keypath)
}
}
}
// MARK: Internal
var configurations = [SwiftUIView<AnimatedSwitch, Void>.Configuration]()
// MARK: Private
private let animation: LottieAnimation?
private var configuration: LottieConfiguration = .shared
private var isOn: Binding<Bool>?
}
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Controls/LottieSwitch.swift
|
Swift
|
unknown
| 4,868
|
// Created by Cal Stephens on 8/11/23.
// Copyright © 2023 Airbnb Inc. All rights reserved.
#if canImport(UIKit)
import UIKit
/// The control base type for this platform.
/// - `UIControl` on iOS / tvOS and `NSControl` on macOS.
public typealias LottieControlType = UIControl
/// The `State` type of `LottieControlType`
/// - `UIControl.State` on iOS / tvOS and `NSControl.StateValue` on macOS.
public typealias LottieControlState = UIControl.State
/// The event type handled by the `LottieControlType` component for this platform.
/// - `UIControl.Event` on iOS / tvOS and `LottieNSControlEvent` on macOS.
public typealias LottieControlEvent = UIControl.Event
extension LottieControlEvent {
var id: AnyHashable {
rawValue
}
}
#else
import AppKit
/// The control base type for this platform.
/// - `UIControl` on iOS / tvOS and `NSControl` on macOS.
public typealias LottieControlType = NSControl
/// The `State` type of `LottieControlType`
/// - `UIControl.State` on iOS / tvOS and `NSControl.StateValue` on macOS.
public typealias LottieControlState = LottieNSControlState
/// AppKit equivalent of `UIControl.State` for `AnimatedControl`
public enum LottieNSControlState: UInt, RawRepresentable {
/// The normal, or default, state of a control where the control is enabled but neither selected nor highlighted.
case normal
/// The highlighted state of a control.
case highlighted
}
/// The event type handled by the `LottieControlType` component for this platform.
/// - `UIControl.Event` on iOS / tvOS and `LottieNSControlEvent` on macOS.
public typealias LottieControlEvent = LottieNSControlEvent
public struct LottieNSControlEvent: Equatable {
// MARK: Lifecycle
public init(_ event: NSEvent.EventType, inside: Bool) {
self.event = event
self.inside = inside
}
// MARK: Public
/// macOS equivalent to `UIControl.Event.touchDown`
public static let touchDown = LottieNSControlEvent(.leftMouseDown, inside: true)
/// macOS equivalent to `UIControl.Event.touchUpInside`
public static let touchUpInside = LottieNSControlEvent(.leftMouseUp, inside: true)
/// macOS equivalent to `UIControl.Event.touchUpInside`
public static let touchUpOutside = LottieNSControlEvent(.leftMouseUp, inside: false)
/// The underlying `NSEvent.EventType` of this event, which is roughly equivalent to `UIControl.Event`
public var event: NSEvent.EventType
/// Whether or not the mouse must be inside the control.
public var inside: Bool
// MARK: Internal
var id: AnyHashable {
[AnyHashable(event.rawValue), AnyHashable(inside)]
}
}
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Controls/LottieViewType.swift
|
Swift
|
unknown
| 2,606
|
//
// LRUDotLottieCache.swift
// Lottie
//
// Created by Evandro Hoffmann on 20/10/22.
//
import Foundation
// MARK: - DotLottieCache
/// A DotLottie Cache that will store lottie files up to `cacheSize`.
///
/// Once `cacheSize` is reached, the least recently used lottie will be ejected.
/// The default size of the cache is 100.
public class DotLottieCache: DotLottieCacheProvider {
// MARK: Lifecycle
public init() {
cache.countLimit = Self.defaultCacheCountLimit
}
// MARK: Public
/// The global shared Cache.
public static let sharedCache = DotLottieCache()
/// The size of the cache.
public var cacheSize = defaultCacheCountLimit {
didSet {
cache.countLimit = cacheSize
}
}
/// Clears the Cache.
public func clearCache() {
cache.removeAllValues()
}
public func file(forKey key: String) -> DotLottieFile? {
cache.value(forKey: key)
}
public func setFile(_ lottie: DotLottieFile, forKey key: String) {
cache.setValue(lottie, forKey: key)
}
// MARK: Private
private static let defaultCacheCountLimit = 100
/// The underlying storage of this cache.
/// - We use the `LRUCache` library instead of `NSCache`, because `NSCache`
/// clears all cached values when the app is backgrounded instead of
/// only when the app receives a memory warning notification.
private var cache = LRUCache<String, DotLottieFile>()
}
// MARK: Sendable
// DotLottieCacheProvider has a Sendable requirement, but we can't
// redesign DotLottieCache to be properly Sendable without making breaking changes.
// swiftlint:disable:next no_unchecked_sendable
extension DotLottieCache: @unchecked Sendable { }
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/DotLottie/Cache/DotLottieCache.swift
|
Swift
|
unknown
| 1,684
|
//
// DotLottieCacheProvider.swift
// Lottie
//
// Created by Evandro Hoffmann on 20/10/22.
//
/// `DotLottieCacheProvider` is a protocol that describes a DotLottie Cache.
/// DotLottie Cache is used when loading `DotLottie` models. Using a DotLottie Cache
/// can increase performance when loading an animation multiple times.
///
/// Lottie comes with a prebuilt LRU DotLottie Cache.
public protocol DotLottieCacheProvider: Sendable {
func file(forKey: String) -> DotLottieFile?
func setFile(_ lottie: DotLottieFile, forKey: String)
func clearCache()
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/DotLottie/Cache/DotLottieCacheProvider.swift
|
Swift
|
unknown
| 569
|
//
// DotLottieConfiguration.swift
// Lottie
//
// Created by Evandro Hoffmann on 19/10/22.
//
// MARK: - DotLottieConfiguration
/// The `DotLottieConfiguration` model holds the presets extracted from DotLottieAnimation
/// - The presets are used as input to setup `LottieAnimationView` before playing the animation.
public struct DotLottieConfiguration {
// MARK: Public
/// id of the animation
public var id: String
/// Loop behavior of animation
public var loopMode: LottieLoopMode
/// Playback speed of animation
public var speed: Double
/// Animation Image Provider
public var imageProvider: AnimationImageProvider? {
dotLottieImageProvider
}
// MARK: Internal
/// The underlying `DotLottieImageProvider` used by this dotLottie animation
var dotLottieImageProvider: DotLottieImageProvider?
}
// MARK: - DotLottieConfigurationComponents
/// Components of the `DotLottieConfiguration` to apply to the `LottieAnimationView`.
/// - When using `LottieView`, if the component is selected to be applied it will
/// override any value provided via other `LottieView` APIs.
public struct DotLottieConfigurationComponents: OptionSet {
// MARK: Lifecycle
public init(rawValue: Int) {
self.rawValue = rawValue
}
// MARK: Public
/// `DotLottieConfiguration.imageProvider` will be applied to the `LottieAnimationView`
/// - When using `LottieView`, the image provider from the dotLottie animation will override
/// the image provider applied manually using `LottieView.imageProvider(...)`.
public static let imageProvider = DotLottieConfigurationComponents(rawValue: 1 << 0)
/// `DotLottieConfigurationMode.loopMode` will be applied to the `LottieAnimationView`.
/// - When using `LottieView`, the loop mode from the dotLottie animation will override
/// the loopMode applied by any playback method.
public static let loopMode = DotLottieConfigurationComponents(rawValue: 1 << 1)
/// `DotLottieConfigurationMode.speed` will be applied to the `LottieAnimationView`.
/// - When using `LottieView`, the speed from the dotLottie animation will override
/// the speed applied manually using `LottieView.animationSpeed(...)`.
public static let animationSpeed = DotLottieConfigurationComponents(rawValue: 1 << 2)
public static let all: DotLottieConfigurationComponents = [.imageProvider, .loopMode, .animationSpeed]
public static let none: DotLottieConfigurationComponents = []
public let rawValue: Int
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/DotLottie/DotLottieConfiguration.swift
|
Swift
|
unknown
| 2,499
|
//
// DotLottie.swift
// Lottie
//
// Created by Evandro Harrison Hoffmann on 27/06/2020.
//
import Foundation
// MARK: - DotLottieFile
/// Detailed .lottie file structure
public final class DotLottieFile {
// MARK: Lifecycle
/// Loads `DotLottie` from `Data` object containing a compressed animation.
///
/// - Parameters:
/// - data: Data of .lottie file
/// - filename: Name of .lottie file
/// - Returns: Deserialized `DotLottie`. Optional.
init(data: Data, filename: String) throws {
fileUrl = DotLottieUtils.tempDirectoryURL.appendingPathComponent(filename.asFilename())
try decompress(data: data, to: fileUrl)
}
// MARK: Public
/// Definition for a single animation within a `DotLottieFile`
public struct Animation {
public let animation: LottieAnimation
public let configuration: DotLottieConfiguration
}
/// List of `LottieAnimation` in the file
public private(set) var animations: [Animation] = []
// MARK: Internal
/// Image provider for animations
private(set) var imageProvider: DotLottieImageProvider?
/// Animations folder url
lazy var animationsUrl: URL = fileUrl.appendingPathComponent("\(DotLottieFile.animationsFolderName)")
/// All files in animations folder
lazy var animationUrls: [URL] = FileManager.default.urls(for: animationsUrl) ?? []
/// Images folder url
lazy var imagesUrl: URL = fileUrl.appendingPathComponent("\(DotLottieFile.imagesFolderName)")
/// All images in images folder
lazy var imageUrls: [URL] = FileManager.default.urls(for: imagesUrl) ?? []
/// The `LottieAnimation` and `DotLottieConfiguration` for the given animation ID in this file
func animation(for id: String? = nil) -> DotLottieFile.Animation? {
if let id {
return animations.first(where: { $0.configuration.id == id })
} else {
return animations.first
}
}
/// The `LottieAnimation` and `DotLottieConfiguration` for the given animation index in this file
func animation(at index: Int) -> DotLottieFile.Animation? {
guard index < animations.count else { return nil }
return animations[index]
}
// MARK: Private
private static let manifestFileName = "manifest.json"
private static let animationsFolderName = "animations"
private static let imagesFolderName = "images"
private let fileUrl: URL
/// Decompresses .lottie file from `URL` and saves to local temp folder
///
/// - Parameters:
/// - url: url to .lottie file
/// - destinationURL: url to destination of decompression contents
private func decompress(from url: URL, to destinationURL: URL) throws {
try? FileManager.default.removeItem(at: destinationURL)
try FileManager.default.createDirectory(at: destinationURL, withIntermediateDirectories: true, attributes: nil)
try FileManager.default.unzipItem(at: url, to: destinationURL)
try loadContent()
try? FileManager.default.removeItem(at: destinationURL)
try? FileManager.default.removeItem(at: url)
}
/// Decompresses .lottie file from `Data` and saves to local temp folder
///
/// - Parameters:
/// - url: url to .lottie file
/// - destinationURL: url to destination of decompression contents
private func decompress(data: Data, to destinationURL: URL) throws {
let url = destinationURL.appendingPathExtension("lottie")
try FileManager.default.createDirectory(at: destinationURL, withIntermediateDirectories: true, attributes: nil)
try data.write(to: url)
try decompress(from: url, to: destinationURL)
}
/// Loads file content to memory
private func loadContent() throws {
imageProvider = DotLottieImageProvider(filepath: imagesUrl)
animations = try loadManifest().animations.map { dotLottieAnimation in
let animation = try dotLottieAnimation.animation(url: animationsUrl)
let configuration = DotLottieConfiguration(
id: dotLottieAnimation.id,
loopMode: dotLottieAnimation.loopMode,
speed: dotLottieAnimation.animationSpeed,
dotLottieImageProvider: imageProvider)
return DotLottieFile.Animation(
animation: animation,
configuration: configuration)
}
}
private func loadManifest() throws -> DotLottieManifest {
let path = fileUrl.appendingPathComponent(DotLottieFile.manifestFileName)
return try DotLottieManifest.load(from: path)
}
}
extension String {
// MARK: Fileprivate
fileprivate func asFilename() -> String {
lastPathComponent().removingPathExtension()
}
// MARK: Private
private func lastPathComponent() -> String {
(self as NSString).lastPathComponent
}
private func removingPathExtension() -> String {
(self as NSString).deletingPathExtension
}
}
// MARK: - DotLottieFile + Sendable
// Mark `DotLottieFile` as `@unchecked Sendable` to allow it to be used when strict concurrency is enabled.
// In the future, it may be necessary to make changes to the internal implementation of `DotLottieFile`
// to make it truly thread-safe.
// swiftlint:disable:next no_unchecked_sendable
extension DotLottieFile: @unchecked Sendable { }
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/DotLottie/DotLottieFile.swift
|
Swift
|
unknown
| 5,098
|
//
// DotLottieFileHelpers.swift
// Lottie
//
// Created by Evandro Hoffmann on 20/10/22.
//
import Foundation
extension DotLottieFile {
public enum SynchronouslyBlockingCurrentThread {
/// Loads an DotLottie from a specific filepath synchronously. Returns a `Result<DotLottieFile, Error>`
/// Please use the asynchronous methods whenever possible. This operation will block the Thread it is running in.
///
/// - Parameter filepath: The absolute filepath of the lottie to load. EG "/User/Me/starAnimation.lottie"
/// - Parameter dotLottieCache: A cache for holding loaded lotties. Defaults to `LRUDotLottieCache.sharedCache`. Optional.
public static func loadedFrom(
filepath: String,
dotLottieCache: DotLottieCacheProvider? = DotLottieCache.sharedCache)
-> Result<DotLottieFile, Error>
{
LottieLogger.shared.assert(
!Thread.isMainThread,
"`DotLottieFile.SynchronouslyBlockingCurrentThread` methods shouldn't be called on the main thread.")
/// Check cache for lottie
if
let dotLottieCache,
let lottie = dotLottieCache.file(forKey: filepath)
{
return .success(lottie)
}
do {
/// Decode the lottie.
let url = URL(fileURLWithPath: filepath)
let data = try Data(contentsOf: url)
let lottie = try DotLottieFile(data: data, filename: url.deletingPathExtension().lastPathComponent)
dotLottieCache?.setFile(lottie, forKey: filepath)
return .success(lottie)
} catch {
/// Decoding Error.
return .failure(error)
}
}
/// Loads a DotLottie model from a bundle by its name synchronously. Returns a `Result<DotLottieFile, Error>`
/// Please use the asynchronous methods whenever possible. This operation will block the Thread it is running in.
///
/// - Parameter name: The name of the lottie file without the lottie extension. EG "StarAnimation"
/// - Parameter bundle: The bundle in which the lottie is located. Defaults to `Bundle.main`
/// - Parameter subdirectory: A subdirectory in the bundle in which the lottie is located. Optional.
/// - Parameter dotLottieCache: A cache for holding loaded lotties. Defaults to `LRUDotLottieCache.sharedCache`. Optional.
public static func named(
_ name: String,
bundle: Bundle = Bundle.main,
subdirectory: String? = nil,
dotLottieCache: DotLottieCacheProvider? = DotLottieCache.sharedCache)
-> Result<DotLottieFile, Error>
{
LottieLogger.shared.assert(
!Thread.isMainThread,
"`DotLottieFile.SynchronouslyBlockingCurrentThread` methods shouldn't be called on the main thread.")
/// Create a cache key for the lottie.
let cacheKey = bundle.bundlePath + (subdirectory ?? "") + "/" + name
/// Check cache for lottie
if
let dotLottieCache,
let lottie = dotLottieCache.file(forKey: cacheKey)
{
return .success(lottie)
}
do {
/// Decode animation.
let data = try bundle.dotLottieData(name, subdirectory: subdirectory)
let lottie = try DotLottieFile(data: data, filename: name)
dotLottieCache?.setFile(lottie, forKey: cacheKey)
return .success(lottie)
} catch {
/// Decoding error.
LottieLogger.shared.warn("Error when decoding lottie \"\(name)\": \(error)")
return .failure(error)
}
}
/// Loads an DotLottie from a data synchronously. Returns a `Result<DotLottieFile, Error>`
///
/// Please use the asynchronous methods whenever possible. This operation will block the Thread it is running in.
///
/// - Parameters:
/// - data: The data(`Foundation.Data`) object to load DotLottie from
/// - filename: The name of the lottie file without the lottie extension. eg. "StarAnimation"
public static func loadedFrom(
data: Data,
filename: String)
-> Result<DotLottieFile, Error>
{
LottieLogger.shared.assert(
!Thread.isMainThread,
"`DotLottieFile.SynchronouslyBlockingCurrentThread` methods shouldn't be called on the main thread.")
do {
let dotLottieFile = try DotLottieFile(data: data, filename: filename)
return .success(dotLottieFile)
} catch {
return .failure(error)
}
}
}
/// Loads a DotLottie model from a bundle by its name. Returns `nil` if a file is not found.
///
/// - Parameter name: The name of the lottie file without the lottie extension. EG "StarAnimation"
/// - Parameter bundle: The bundle in which the lottie is located. Defaults to `Bundle.main`
/// - Parameter subdirectory: A subdirectory in the bundle in which the lottie is located. Optional.
/// - Parameter dotLottieCache: A cache for holding loaded lotties. Defaults to `LRUDotLottieCache.sharedCache`. Optional.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public static func named(
_ name: String,
bundle: Bundle = Bundle.main,
subdirectory: String? = nil,
dotLottieCache: DotLottieCacheProvider? = DotLottieCache.sharedCache)
async throws -> DotLottieFile
{
try await withCheckedThrowingContinuation { continuation in
DotLottieFile.named(name, bundle: bundle, subdirectory: subdirectory, dotLottieCache: dotLottieCache) { result in
continuation.resume(with: result)
}
}
}
/// Loads a DotLottie model from a bundle by its name. Returns `nil` if a file is not found.
///
/// - Parameter name: The name of the lottie file without the lottie extension. EG "StarAnimation"
/// - Parameter bundle: The bundle in which the lottie is located. Defaults to `Bundle.main`
/// - Parameter subdirectory: A subdirectory in the bundle in which the lottie is located. Optional.
/// - Parameter dotLottieCache: A cache for holding loaded lotties. Defaults to `LRUDotLottieCache.sharedCache`. Optional.
/// - Parameter dispatchQueue: A dispatch queue used to load animations. Defaults to `DispatchQueue.global()`. Optional.
/// - Parameter handleResult: A closure to be called when the file has loaded.
public static func named(
_ name: String,
bundle: Bundle = Bundle.main,
subdirectory: String? = nil,
dotLottieCache: DotLottieCacheProvider? = DotLottieCache.sharedCache,
dispatchQueue: DispatchQueue = .dotLottie,
handleResult: @escaping (Result<DotLottieFile, Error>) -> Void)
{
dispatchQueue.async {
let result = SynchronouslyBlockingCurrentThread.named(
name,
bundle: bundle,
subdirectory: subdirectory,
dotLottieCache: dotLottieCache)
DispatchQueue.main.async {
handleResult(result)
}
}
}
/// Loads an DotLottie from a specific filepath.
/// - Parameter filepath: The absolute filepath of the lottie to load. EG "/User/Me/starAnimation.lottie"
/// - Parameter dotLottieCache: A cache for holding loaded lotties. Defaults to `LRUDotLottieCache.sharedCache`. Optional.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public static func loadedFrom(
filepath: String,
dotLottieCache: DotLottieCacheProvider? = DotLottieCache.sharedCache)
async throws -> DotLottieFile
{
try await withCheckedThrowingContinuation { continuation in
DotLottieFile.loadedFrom(filepath: filepath, dotLottieCache: dotLottieCache) { result in
continuation.resume(with: result)
}
}
}
/// Loads an DotLottie from a specific filepath.
/// - Parameter filepath: The absolute filepath of the lottie to load. EG "/User/Me/starAnimation.lottie"
/// - Parameter dotLottieCache: A cache for holding loaded lotties. Defaults to `LRUDotLottieCache.sharedCache`. Optional.
/// - Parameter dispatchQueue: A dispatch queue used to load animations. Defaults to `DispatchQueue.global()`. Optional.
/// - Parameter handleResult: A closure to be called when the file has loaded.
public static func loadedFrom(
filepath: String,
dotLottieCache: DotLottieCacheProvider? = DotLottieCache.sharedCache,
dispatchQueue: DispatchQueue = .dotLottie,
handleResult: @escaping (Result<DotLottieFile, Error>) -> Void)
{
dispatchQueue.async {
let result = SynchronouslyBlockingCurrentThread.loadedFrom(
filepath: filepath,
dotLottieCache: dotLottieCache)
DispatchQueue.main.async {
handleResult(result)
}
}
}
/// Loads a DotLottie model from the asset catalog by its name. Returns `nil` if a lottie is not found.
/// - Parameter name: The name of the lottie file in the asset catalog. EG "StarAnimation"
/// - Parameter bundle: The bundle in which the lottie is located. Defaults to `Bundle.main`
/// - Parameter dotLottieCache: A cache for holding loaded lottie files. Defaults to `LRUDotLottieCache.sharedCache` Optional.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public static func asset(
named name: String,
bundle: Bundle = Bundle.main,
dotLottieCache: DotLottieCacheProvider? = DotLottieCache.sharedCache)
async throws -> DotLottieFile
{
try await withCheckedThrowingContinuation { continuation in
DotLottieFile.asset(named: name, bundle: bundle, dotLottieCache: dotLottieCache) { result in
continuation.resume(with: result)
}
}
}
/// Loads a DotLottie model from the asset catalog by its name. Returns `nil` if a lottie is not found.
/// - Parameter name: The name of the lottie file in the asset catalog. EG "StarAnimation"
/// - Parameter bundle: The bundle in which the lottie is located. Defaults to `Bundle.main`
/// - Parameter dotLottieCache: A cache for holding loaded lottie files. Defaults to `LRUDotLottieCache.sharedCache` Optional.
/// - Parameter dispatchQueue: A dispatch queue used to load animations. Defaults to `DispatchQueue.global()`. Optional.
/// - Parameter handleResult: A closure to be called when the file has loaded.
public static func asset(
named name: String,
bundle: Bundle = Bundle.main,
dotLottieCache: DotLottieCacheProvider? = DotLottieCache.sharedCache,
dispatchQueue: DispatchQueue = .dotLottie,
handleResult: @escaping (Result<DotLottieFile, Error>) -> Void)
{
dispatchQueue.async {
/// Create a cache key for the lottie.
let cacheKey = bundle.bundlePath + "/" + name
/// Check cache for lottie
if
let dotLottieCache,
let lottie = dotLottieCache.file(forKey: cacheKey)
{
/// If found, return the lottie.
DispatchQueue.main.async {
handleResult(.success(lottie))
}
return
}
do {
/// Load data from Asset
let data = try Data(assetName: name, in: bundle)
/// Decode lottie.
let lottie = try DotLottieFile(data: data, filename: name)
dotLottieCache?.setFile(lottie, forKey: cacheKey)
DispatchQueue.main.async {
handleResult(.success(lottie))
}
} catch {
/// Decoding error.
DispatchQueue.main.async {
handleResult(.failure(error))
}
}
}
}
/// Loads a DotLottie animation asynchronously from the URL.
///
/// - Parameter url: The url to load the animation from.
/// - Parameter animationCache: A cache for holding loaded animations. Defaults to `LRUAnimationCache.sharedCache`. Optional.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public static func loadedFrom(
url: URL,
session: URLSession = .shared,
dotLottieCache: DotLottieCacheProvider? = DotLottieCache.sharedCache)
async throws -> DotLottieFile
{
try await withCheckedThrowingContinuation { continuation in
DotLottieFile.loadedFrom(url: url, session: session, dotLottieCache: dotLottieCache) { result in
continuation.resume(with: result)
}
}
}
/// Loads a DotLottie animation asynchronously from the URL.
///
/// - Parameter url: The url to load the animation from.
/// - Parameter animationCache: A cache for holding loaded animations. Defaults to `LRUAnimationCache.sharedCache`. Optional.
/// - Parameter handleResult: A closure to be called when the animation has loaded.
public static func loadedFrom(
url: URL,
session: URLSession = .shared,
dotLottieCache: DotLottieCacheProvider? = DotLottieCache.sharedCache,
handleResult: @escaping (Result<DotLottieFile, Error>) -> Void)
{
if let dotLottieCache, let lottie = dotLottieCache.file(forKey: url.absoluteString) {
handleResult(.success(lottie))
} else {
let task = session.dataTask(with: url) { data, _, error in
do {
if let error {
throw error
}
guard let data else {
throw DotLottieError.noDataLoaded
}
let lottie = try DotLottieFile(data: data, filename: url.deletingPathExtension().lastPathComponent)
DispatchQueue.main.async {
dotLottieCache?.setFile(lottie, forKey: url.absoluteString)
handleResult(.success(lottie))
}
} catch {
DispatchQueue.main.async {
handleResult(.failure(error))
}
}
}
task.resume()
}
}
/// Loads an DotLottie from a data asynchronously.
///
/// - Parameters:
/// - data: The data(`Foundation.Data`) object to load DotLottie from
/// - filename: The name of the lottie file without the lottie extension. eg. "StarAnimation"
/// - dispatchQueue: A dispatch queue used to load animations. Defaults to `DispatchQueue.global()`. Optional.
/// - handleResult: A closure to be called when the file has loaded.
public static func loadedFrom(
data: Data,
filename: String,
dispatchQueue: DispatchQueue = .dotLottie,
handleResult: @escaping (Result<DotLottieFile, Error>) -> Void)
{
dispatchQueue.async {
do {
let dotLottie = try DotLottieFile(data: data, filename: filename)
DispatchQueue.main.async {
handleResult(.success(dotLottie))
}
} catch {
DispatchQueue.main.async {
handleResult(.failure(error))
}
}
}
}
/// Loads an DotLottie from a data asynchronously.
///
/// - Parameters:
/// - data: The data(`Foundation.Data`) object to load DotLottie from
/// - filename: The name of the lottie file without the lottie extension. eg. "StarAnimation"
/// - dispatchQueue: A dispatch queue used to load animations. Defaults to `DispatchQueue.global()`. Optional.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public static func loadedFrom(
data: Data,
filename: String,
dispatchQueue: DispatchQueue = .dotLottie)
async throws -> DotLottieFile
{
try await withCheckedThrowingContinuation { continuation in
loadedFrom(data: data, filename: filename, dispatchQueue: dispatchQueue) { result in
continuation.resume(with: result)
}
}
}
}
extension DispatchQueue {
/// A serial dispatch queue ensures that IO related to loading dot Lottie files don't overlap,
/// which can trigger file loading errors due to concurrent unzipping on a single archive.
public static let dotLottie = DispatchQueue(
label: "com.airbnb.lottie.dot-lottie",
qos: .userInitiated)
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/DotLottie/DotLottieFileHelpers.swift
|
Swift
|
unknown
| 15,334
|
//
// AnimationKeypath.swift
// lottie-swift
//
// Created by Brandon Withrow on 2/4/19.
//
/// `AnimationKeypath` is an object that describes a keypath search for nodes in the
/// animation JSON. `AnimationKeypath` matches views and properties inside of `LottieAnimationView`
/// to their backing `LottieAnimation` model by name.
///
/// A keypath can be used to set properties on an existing animation, or can be validated
/// with an existing `LottieAnimation`.
///
/// `AnimationKeypath` can describe a specific object, or can use wildcards for fuzzy matching
/// of objects. Acceptable wildcards are either "*" (star) or "**" (double star).
/// Single star will search a single depth for the next object.
/// Double star will search any depth.
///
/// Read More at https://airbnb.io/lottie/#/ios?id=dynamic-animation-properties
///
/// EG:
/// @"Layer.Shape Group.Stroke 1.Color"
/// Represents a specific color node on a specific stroke.
///
/// @"**.Stroke 1.Color"
/// Represents the color node for every Stroke named "Stroke 1" in the animation.
public struct AnimationKeypath: Hashable, ExpressibleByStringLiteral {
// MARK: Lifecycle
/// Creates a keypath from a dot-separated string. The string is separated by "."
public init(keypath: String) {
keys = keypath.components(separatedBy: ".")
}
/// Creates a keypath from a dot-separated string
public init(stringLiteral: String) {
self.init(keypath: stringLiteral)
}
/// Creates a keypath from a list of strings.
public init(keys: [String]) {
self.keys = keys
}
// MARK: Public
/// The dot-separated key values that represent this keypath.
public internal(set) var keys: [String]
/// The `String` representation of this keypath
public var string: String {
keys.joined(separator: ".")
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/DynamicProperties/AnimationKeypath.swift
|
Swift
|
unknown
| 1,808
|
//
// AnyValueProvider.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/30/19.
//
import Foundation
// MARK: - AnyValueProvider
/// `AnyValueProvider` is a protocol that return animation data for a property at a
/// given time. Every frame a `LottieAnimationView` queries all of its properties and asks
/// if their ValueProvider has an update. If it does the LottieAnimationView will read the
/// property and update that portion of the animation.
///
/// Value Providers can be used to dynamically set animation properties at run time.
public protocol AnyValueProvider {
/// The Type of the value provider
var valueType: Any.Type { get }
/// The type-erased storage for this Value Provider
var typeErasedStorage: AnyValueProviderStorage { get }
/// Asks the provider if it has an update for the given frame.
func hasUpdate(frame: AnimationFrameTime) -> Bool
}
extension AnyValueProvider {
/// Asks the provider to update the container with its value for the frame.
public func value(frame: AnimationFrameTime) -> Any {
typeErasedStorage.value(frame: frame)
}
}
// MARK: - ValueProvider
/// A base protocol for strongly-typed Value Providers
protocol ValueProvider: AnyValueProvider {
associatedtype Value: AnyInterpolatable
/// The strongly-typed storage for this Value Provider
var storage: ValueProviderStorage<Value> { get }
}
extension ValueProvider {
public var typeErasedStorage: AnyValueProviderStorage {
switch storage {
case .closure(let typedClosure):
return .closure(typedClosure)
case .singleValue(let typedValue):
return .singleValue(typedValue)
case .keyframes(let keyframes):
return .keyframes(
keyframes.map { keyframe in
keyframe.withValue(keyframe.value as Any)
},
interpolate: storage.value(frame:))
}
}
}
// MARK: - ValueProviderStorage
/// The underlying storage of a `ValueProvider`
public enum ValueProviderStorage<T: AnyInterpolatable> {
/// The value provider stores a single value that is used on all frames
case singleValue(T)
/// The value provider stores a group of keyframes
/// - The main-thread rendering engine interpolates values in these keyframes
/// using `T`'s `Interpolatable` implementation.
/// - The Core Animation rendering engine constructs a `CAKeyframeAnimation`
/// using these keyframes. The Core Animation render server performs
/// the interpolation, without calling `T`'s `Interpolatable` implementation.
case keyframes([Keyframe<T>])
/// The value provider stores a closure that is invoked on every frame
/// - This is only supported by the main-thread rendering engine
case closure((AnimationFrameTime) -> T)
// MARK: Internal
func value(frame: AnimationFrameTime) -> T {
switch self {
case .singleValue(let value):
return value
case .closure(let closure):
return closure(frame)
case .keyframes(let keyframes):
return KeyframeInterpolator(keyframes: ContiguousArray(keyframes)).storage.value(frame: frame)
}
}
}
// MARK: - AnyValueProviderStorage
/// A type-erased representation of `ValueProviderStorage`
public enum AnyValueProviderStorage {
/// The value provider stores a single value that is used on all frames
case singleValue(Any)
/// The value provider stores a group of keyframes
/// - Since we can't interpolate a type-erased `KeyframeGroup`,
/// the interpolation has to be performed in the `interpolate` closure.
case keyframes([Keyframe<Any>], interpolate: (AnimationFrameTime) -> Any)
/// The value provider stores a closure that is invoked on every frame
case closure((AnimationFrameTime) -> Any)
// MARK: Internal
func value(frame: AnimationFrameTime) -> Any {
switch self {
case .singleValue(let value):
return value
case .closure(let closure):
return closure(frame)
case .keyframes(_, let valueForFrame):
return valueForFrame(frame)
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/DynamicProperties/AnyValueProvider.swift
|
Swift
|
unknown
| 4,004
|
//
// ColorValueProvider.swift
// lottie-swift
//
// Created by Brandon Withrow on 2/4/19.
//
import CoreGraphics
import Foundation
// MARK: - ColorValueProvider
/// A `ValueProvider` that returns a CGColor Value
public final class ColorValueProvider: ValueProvider {
// MARK: Lifecycle
/// Initializes with a block provider
public init(block: @escaping ColorValueBlock) {
self.block = block
color = LottieColor(r: 0, g: 0, b: 0, a: 1)
keyframes = nil
identity = UUID()
}
/// Initializes with a single color.
public init(_ color: LottieColor) {
self.color = color
block = nil
keyframes = nil
hasUpdate = true
identity = color
}
/// Initializes with multiple colors, with timing information
public init(_ keyframes: [Keyframe<LottieColor>]) {
self.keyframes = keyframes
color = LottieColor(r: 0, g: 0, b: 0, a: 1)
block = nil
hasUpdate = true
identity = keyframes
}
// MARK: Public
/// Returns a LottieColor for a CGColor(Frame Time)
public typealias ColorValueBlock = (CGFloat) -> LottieColor
/// The color value of the provider.
public var color: LottieColor {
didSet {
hasUpdate = true
}
}
// MARK: ValueProvider Protocol
public var valueType: Any.Type {
LottieColor.self
}
public var storage: ValueProviderStorage<LottieColor> {
if let block {
return .closure { frame in
self.hasUpdate = false
return block(frame)
}
} else if let keyframes {
return .keyframes(keyframes)
} else {
hasUpdate = false
return .singleValue(color)
}
}
public func hasUpdate(frame _: CGFloat) -> Bool {
if block != nil {
return true
}
return hasUpdate
}
// MARK: Private
private var hasUpdate = true
private var block: ColorValueBlock?
private var keyframes: [Keyframe<LottieColor>]?
private var identity: AnyHashable
}
// MARK: Equatable
extension ColorValueProvider: Equatable {
public static func ==(_ lhs: ColorValueProvider, _ rhs: ColorValueProvider) -> Bool {
lhs.identity == rhs.identity
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/DynamicProperties/ValueProviders/ColorValueProvider.swift
|
Swift
|
unknown
| 2,119
|
//
// DoubleValueProvider.swift
// lottie-swift
//
// Created by Brandon Withrow on 2/4/19.
//
import CoreGraphics
import Foundation
// MARK: - FloatValueProvider
/// A `ValueProvider` that returns a CGFloat Value
public final class FloatValueProvider: ValueProvider {
// MARK: Lifecycle
/// Initializes with a block provider
public init(block: @escaping CGFloatValueBlock) {
self.block = block
float = 0
identity = UUID()
}
/// Initializes with a single float.
public init(_ float: CGFloat) {
self.float = float
block = nil
hasUpdate = true
identity = float
}
// MARK: Public
/// Returns a CGFloat for a CGFloat(Frame Time)
public typealias CGFloatValueBlock = (CGFloat) -> CGFloat
public var float: CGFloat {
didSet {
hasUpdate = true
}
}
// MARK: ValueProvider Protocol
public var valueType: Any.Type {
LottieVector1D.self
}
public var storage: ValueProviderStorage<LottieVector1D> {
if let block {
return .closure { frame in
self.hasUpdate = false
return LottieVector1D(Double(block(frame)))
}
} else {
hasUpdate = false
return .singleValue(LottieVector1D(Double(float)))
}
}
public func hasUpdate(frame _: CGFloat) -> Bool {
if block != nil {
return true
}
return hasUpdate
}
// MARK: Private
private var hasUpdate = true
private var block: CGFloatValueBlock?
private var identity: AnyHashable
}
// MARK: Equatable
extension FloatValueProvider: Equatable {
public static func ==(_ lhs: FloatValueProvider, _ rhs: FloatValueProvider) -> Bool {
lhs.identity == rhs.identity
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/DynamicProperties/ValueProviders/FloatValueProvider.swift
|
Swift
|
unknown
| 1,672
|
//
// GradientValueProvider.swift
// lottie-swift
//
// Created by Enrique Bermúdez on 10/27/19.
//
import CoreGraphics
import Foundation
// MARK: - GradientValueProvider
/// A `ValueProvider` that returns a Gradient Color Value.
public final class GradientValueProvider: ValueProvider {
// MARK: Lifecycle
/// Initializes with a block provider.
public init(
block: @escaping ColorsValueBlock,
locations: ColorLocationsBlock? = nil)
{
self.block = block
locationsBlock = locations
colors = []
self.locations = []
identity = UUID()
}
/// Initializes with an array of colors.
public init(
_ colors: [LottieColor],
locations: [Double] = [])
{
self.colors = colors
self.locations = locations
identity = [AnyHashable(colors), AnyHashable(locations)]
updateValueArray()
hasUpdate = true
}
// MARK: Public
/// Returns a [LottieColor] for a CGFloat(Frame Time).
public typealias ColorsValueBlock = (CGFloat) -> [LottieColor]
/// Returns a [Double](Color locations) for a CGFloat(Frame Time).
public typealias ColorLocationsBlock = (CGFloat) -> [Double]
/// The colors values of the provider.
public var colors: [LottieColor] {
didSet {
updateValueArray()
hasUpdate = true
}
}
/// The color location values of the provider.
public var locations: [Double] {
didSet {
updateValueArray()
hasUpdate = true
}
}
// MARK: ValueProvider Protocol
public var valueType: Any.Type {
[Double].self
}
public var storage: ValueProviderStorage<[Double]> {
if let block {
return .closure { [self] frame in
hasUpdate = false
let newColors = block(frame)
let newLocations = locationsBlock?(frame) ?? []
value = value(from: newColors, locations: newLocations)
return value
}
} else {
return .singleValue(value)
}
}
public func hasUpdate(frame _: CGFloat) -> Bool {
if block != nil || locationsBlock != nil {
return true
}
return hasUpdate
}
// MARK: Private
private var hasUpdate = true
private var block: ColorsValueBlock?
private var locationsBlock: ColorLocationsBlock?
private var value: [Double] = []
private let identity: AnyHashable
private func value(from colors: [LottieColor], locations: [Double]) -> [Double] {
var colorValues = [Double]()
var alphaValues = [Double]()
var shouldAddAlphaValues = false
for i in 0..<colors.count {
if colors[i].a < 1 { shouldAddAlphaValues = true }
let location = locations.count > i
? locations[i]
: (Double(i) / Double(colors.count - 1))
colorValues.append(location)
colorValues.append(colors[i].r)
colorValues.append(colors[i].g)
colorValues.append(colors[i].b)
alphaValues.append(location)
alphaValues.append(colors[i].a)
}
return colorValues + (shouldAddAlphaValues ? alphaValues : [])
}
private func updateValueArray() {
value = value(from: colors, locations: locations)
}
}
// MARK: Equatable
extension GradientValueProvider: Equatable {
public static func ==(_ lhs: GradientValueProvider, _ rhs: GradientValueProvider) -> Bool {
lhs.identity == rhs.identity
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/DynamicProperties/ValueProviders/GradientValueProvider.swift
|
Swift
|
unknown
| 3,280
|
//
// PointValueProvider.swift
// lottie-swift
//
// Created by Brandon Withrow on 2/4/19.
//
import CoreGraphics
import Foundation
// MARK: - PointValueProvider
/// A `ValueProvider` that returns a CGPoint Value
public final class PointValueProvider: ValueProvider {
// MARK: Lifecycle
/// Initializes with a block provider
public init(block: @escaping PointValueBlock) {
self.block = block
point = .zero
identity = UUID()
}
/// Initializes with a single point.
public init(_ point: CGPoint) {
self.point = point
block = nil
hasUpdate = true
identity = [point.x, point.y]
}
// MARK: Public
/// Returns a CGPoint for a CGFloat(Frame Time)
public typealias PointValueBlock = (CGFloat) -> CGPoint
public var point: CGPoint {
didSet {
hasUpdate = true
}
}
// MARK: ValueProvider Protocol
public var valueType: Any.Type {
LottieVector3D.self
}
public var storage: ValueProviderStorage<LottieVector3D> {
if let block {
return .closure { frame in
self.hasUpdate = false
return block(frame).vector3dValue
}
} else {
hasUpdate = false
return .singleValue(point.vector3dValue)
}
}
public func hasUpdate(frame _: CGFloat) -> Bool {
if block != nil {
return true
}
return hasUpdate
}
// MARK: Private
private var hasUpdate = true
private var block: PointValueBlock?
private let identity: AnyHashable
}
// MARK: Equatable
extension PointValueProvider: Equatable {
public static func ==(_ lhs: PointValueProvider, _ rhs: PointValueProvider) -> Bool {
lhs.identity == rhs.identity
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/DynamicProperties/ValueProviders/PointValueProvider.swift
|
Swift
|
unknown
| 1,662
|
//
// SizeValueProvider.swift
// lottie-swift
//
// Created by Brandon Withrow on 2/4/19.
//
import CoreGraphics
import Foundation
// MARK: - SizeValueProvider
/// A `ValueProvider` that returns a CGSize Value
public final class SizeValueProvider: ValueProvider {
// MARK: Lifecycle
/// Initializes with a block provider
public init(block: @escaping SizeValueBlock) {
self.block = block
size = .zero
identity = UUID()
}
/// Initializes with a single size.
public init(_ size: CGSize) {
self.size = size
block = nil
hasUpdate = true
identity = [size.width, size.height]
}
// MARK: Public
/// Returns a CGSize for a CGFloat(Frame Time)
public typealias SizeValueBlock = (CGFloat) -> CGSize
public var size: CGSize {
didSet {
hasUpdate = true
}
}
// MARK: ValueProvider Protocol
public var valueType: Any.Type {
LottieVector3D.self
}
public var storage: ValueProviderStorage<LottieVector3D> {
if let block {
return .closure { frame in
self.hasUpdate = false
return block(frame).vector3dValue
}
} else {
hasUpdate = false
return .singleValue(size.vector3dValue)
}
}
public func hasUpdate(frame _: CGFloat) -> Bool {
if block != nil {
return true
}
return hasUpdate
}
// MARK: Private
private var hasUpdate = true
private var block: SizeValueBlock?
private let identity: AnyHashable
}
// MARK: Equatable
extension SizeValueProvider: Equatable {
public static func ==(_ lhs: SizeValueProvider, _ rhs: SizeValueProvider) -> Bool {
lhs.identity == rhs.identity
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/DynamicProperties/ValueProviders/SizeValueProvider.swift
|
Swift
|
unknown
| 1,648
|
//
// AnimationFontProvider.swift
// Lottie
//
// Created by Brandon Withrow on 8/5/20.
// Copyright © 2020 YurtvilleProds. All rights reserved.
//
import CoreText
// MARK: - AnimationFontProvider
/// Font provider is a protocol that is used to supply fonts to `LottieAnimationView`.
///
public protocol AnimationFontProvider {
func fontFor(family: String, size: CGFloat) -> CTFont?
}
// MARK: - DefaultFontProvider
/// Default Font provider.
public final class DefaultFontProvider: AnimationFontProvider {
// MARK: Lifecycle
public init() { }
// MARK: Public
public func fontFor(family: String, size: CGFloat) -> CTFont? {
CTFontCreateWithName(family as CFString, size, nil)
}
}
// MARK: Equatable
extension DefaultFontProvider: Equatable {
public static func ==(_: DefaultFontProvider, _: DefaultFontProvider) -> Bool {
true
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/FontProvider/AnimationFontProvider.swift
|
Swift
|
unknown
| 871
|
//
// LottieImageProvider.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/25/19.
//
import QuartzCore
// MARK: - AnimationImageProvider
/// Image provider is a protocol that is used to supply images to `LottieAnimationView`.
///
/// Some animations require a reference to an image. The image provider loads and
/// provides those images to the `LottieAnimationView`. Lottie includes a couple of
/// prebuilt Image Providers that supply images from a Bundle, or from a FilePath.
///
/// Additionally custom Image Providers can be made to load images from a URL,
/// or to Cache images.
public protocol AnimationImageProvider {
/// Whether or not the resulting image of this image provider can be cached by Lottie. Defaults to true.
/// If true, Lottie may internally cache the result of `imageForAsset`
var cacheEligible: Bool { get }
/// The image to display for the given `ImageAsset` defined in the `LottieAnimation` JSON file.
func imageForAsset(asset: ImageAsset) -> CGImage?
/// Specifies how the layer's contents are positioned or scaled within its bounds for a given asset.
/// Defaults to `.resize`, which stretches the image to fill the layer.
func contentsGravity(for asset: ImageAsset) -> CALayerContentsGravity
}
extension AnimationImageProvider {
public var cacheEligible: Bool {
true
}
/// The default value is `.resize`, similar to that of `CALayer`.
public func contentsGravity(for _: ImageAsset) -> CALayerContentsGravity {
.resize
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/ImageProvider/AnimationImageProvider.swift
|
Swift
|
unknown
| 1,511
|