Skip to content

Commit 5ca8e78

Browse files
committed
Add Imaege Player to support native SwiftUI View for animation, testing code
1 parent 9589a58 commit 5ca8e78

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

SDWebImageSwiftUI/Classes/WebImage.swift

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,10 @@ public struct WebImage : View {
2222
var retryOnAppear: Bool = true
2323
var cancelOnDisappear: Bool = true
2424

25+
@State var currentFrame: PlatformImage? = nil
26+
2527
@ObservedObject var imageManager: ImageManager
28+
var imagePlayer: SDAnimatedImagePlayer?
2629

2730
/// Create a web image with url, placeholder, custom options and context.
2831
/// - Parameter url: The image url
@@ -31,6 +34,8 @@ public struct WebImage : View {
3134
public init(url: URL?, options: SDWebImageOptions = [], context: [SDWebImageContextOption : Any]? = nil) {
3235
self.url = url
3336
self.options = options
37+
var context = context ?? [:]
38+
context[.animatedImageClass] = SDAnimatedImage.self
3439
self.context = context
3540
self.imageManager = ImageManager(url: url, options: options, context: context)
3641
// load remote image here, SwiftUI sometimes will create a new View struct without calling `onAppear` (like enter EditMode) :)
@@ -41,8 +46,12 @@ public struct WebImage : View {
4146
public var body: some View {
4247
Group {
4348
if imageManager.image != nil {
44-
configurations.reduce(Image(platformImage: imageManager.image!)) { (previous, configuration) in
45-
configuration(previous)
49+
if currentFrame != nil {
50+
configurations.reduce(Image(platformImage: currentFrame!)) { (previous, configuration) in
51+
configuration(previous)
52+
}
53+
} else {
54+
queryFrames()
4655
}
4756
} else {
4857
Group {
@@ -69,6 +78,21 @@ public struct WebImage : View {
6978
}
7079
}
7180
}
81+
82+
func queryFrames() -> some View {
83+
if (imageManager.image as? SDAnimatedImageProvider) != nil {
84+
let imagePlayer = SDAnimatedImagePlayer(provider: (imageManager.image as! SDAnimatedImageProvider))
85+
var result = self
86+
imagePlayer?.animationFrameHandler = { (_, frame) in
87+
result.currentFrame = frame
88+
}
89+
imagePlayer?.startPlaying()
90+
result.imagePlayer = imagePlayer
91+
}
92+
return configurations.reduce(Image(platformImage: imageManager.image!)) { (previous, configuration) in
93+
configuration(previous)
94+
}
95+
}
7296
}
7397

7498
// Layout

0 commit comments

Comments
 (0)