Merge pull request #2882 from dreampiggy/refactory_animated_player_phase2
Refactory AnimatedImageView with player backend, supports more rendering target like WatchKit/SwiftUI
This commit is contained in:
commit
f7821b8285
|
@ -29,6 +29,14 @@
|
|||
- (void)viewDidLoad {
|
||||
[super viewDidLoad];
|
||||
[self configureView];
|
||||
self.navigationItem.rightBarButtonItem = [UIBarButtonItem.alloc initWithTitle:@"Toggle Animation"
|
||||
style:UIBarButtonItemStylePlain
|
||||
target:self
|
||||
action:@selector(toggleAnimation:)];
|
||||
}
|
||||
|
||||
- (void)toggleAnimation:(UIResponder *)sender {
|
||||
self.imageView.isAnimating ? [self.imageView stopAnimating] : [self.imageView startAnimating];
|
||||
}
|
||||
|
||||
@end
|
||||
|
|
|
@ -34,16 +34,27 @@
|
|||
// NSImageView + Static Image
|
||||
self.imageView1.sd_imageIndicator = SDWebImageProgressIndicator.defaultIndicator;
|
||||
[self.imageView1 sd_setImageWithURL:[NSURL URLWithString:@"https://raw.githubusercontent.com/recurser/exif-orientation-examples/master/Landscape_2.jpg"] placeholderImage:nil options:SDWebImageProgressiveLoad];
|
||||
|
||||
// NSImageView + Animated Image
|
||||
self.imageView2.sd_imageIndicator = SDWebImageActivityIndicator.largeIndicator;
|
||||
[self.imageView2 sd_setImageWithURL:[NSURL URLWithString:@"https:raw.githubusercontent.com/onevcat/APNGKit/master/TestImages/APNG-cube.apng"]];
|
||||
NSMenu *menu1 = [[NSMenu alloc] initWithTitle:@"Toggle Animation"];
|
||||
NSMenuItem *item1 = [menu1 addItemWithTitle:@"Toggle Animation" action:@selector(toggleAnimation:) keyEquivalent:@""];
|
||||
item1.tag = 1;
|
||||
self.imageView2.menu = menu1;
|
||||
|
||||
// SDAnimatedImageView + Static Image
|
||||
[self.imageView3 sd_setImageWithURL:[NSURL URLWithString:@"https://nr-platform.s3.amazonaws.com/uploads/platform/published_extension/branding_icon/275/AmazonS3.png"]];
|
||||
|
||||
// SDAnimatedImageView + Animated Image
|
||||
self.imageView4.sd_imageTransition = SDWebImageTransition.fadeTransition;
|
||||
self.imageView4.imageScaling = NSImageScaleProportionallyUpOrDown;
|
||||
self.imageView4.imageAlignment = NSImageAlignLeft; // supports NSImageView's layout properties
|
||||
[self.imageView4 sd_setImageWithURL:[NSURL URLWithString:@"http://littlesvr.ca/apng/images/SteamEngine.webp"] placeholderImage:nil options:SDWebImageForceTransition];
|
||||
NSMenu *menu2 = [[NSMenu alloc] initWithTitle:@"Toggle Animation"];
|
||||
NSMenuItem *item2 = [menu2 addItemWithTitle:@"Toggle Animation" action:@selector(toggleAnimation:) keyEquivalent:@""];
|
||||
item2.tag = 2;
|
||||
self.imageView4.menu = menu2;
|
||||
|
||||
self.clearCacheButton.target = self;
|
||||
self.clearCacheButton.action = @selector(clearCacheButtonClicked:);
|
||||
|
@ -60,6 +71,15 @@
|
|||
}];
|
||||
}
|
||||
|
||||
- (void)toggleAnimation:(NSMenuItem *)sender {
|
||||
NSImageView *imageView = sender.tag == 1 ? self.imageView2 : self.imageView4;
|
||||
if (imageView.animates) {
|
||||
imageView.animates = NO;
|
||||
} else {
|
||||
imageView.animates = YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setRepresentedObject:(id)representedObject {
|
||||
[super setRepresentedObject:representedObject];
|
||||
|
||||
|
|
|
@ -13,7 +13,10 @@
|
|||
|
||||
@interface InterfaceController()
|
||||
|
||||
@property (weak) IBOutlet WKInterfaceImage *imageInterface;
|
||||
@property (weak) IBOutlet WKInterfaceImage *staticImageInterface;
|
||||
@property (weak) IBOutlet WKInterfaceImage *simpleAnimatedImageInterface;
|
||||
@property (weak) IBOutlet WKInterfaceImage *animatedImageInterface;
|
||||
@property (nonatomic, strong) SDAnimatedImagePlayer *player;
|
||||
|
||||
@end
|
||||
|
||||
|
@ -31,12 +34,39 @@
|
|||
// This method is called when watch view controller is about to be visible to user
|
||||
[super willActivate];
|
||||
|
||||
NSString *urlString = @"http://apng.onevcat.com/assets/elephant.png";
|
||||
WKInterfaceImage *imageInterface = self.imageInterface;
|
||||
[imageInterface sd_setImageWithURL:[NSURL URLWithString:urlString] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
|
||||
[self addMenuItemWithItemIcon:WKMenuItemIconTrash title:@"Clear Cache" action:@selector(clearCache)];
|
||||
|
||||
// Static image
|
||||
NSString *urlString1 = @"http://www.ioncannon.net/wp-content/uploads/2011/06/test2.webp";
|
||||
[self.staticImageInterface sd_setImageWithURL:[NSURL URLWithString:urlString1]];
|
||||
|
||||
// Simple animated image playback
|
||||
NSString *urlString2 = @"http://apng.onevcat.com/assets/elephant.png";
|
||||
[self.simpleAnimatedImageInterface sd_setImageWithURL:[NSURL URLWithString:urlString2] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
|
||||
// `WKInterfaceImage` unlike `UIImageView`. Even the image is animated image, you should explicitly call `startAnimating` to play animation.
|
||||
[imageInterface startAnimating];
|
||||
[self.simpleAnimatedImageInterface startAnimating];
|
||||
}];
|
||||
|
||||
// Complicated but the best performance animated image playback
|
||||
// If you use the above method to display this GIF (389 frames), Apple Watch will consume 800+MB and cause OOM
|
||||
// This is actualy the same backend like `SDAnimatedImageView` on iOS, recommend to use
|
||||
NSString *urlString3 = @"https://raw.githubusercontent.com/liyong03/YLGIFImage/master/YLGIFImageDemo/YLGIFImageDemo/joy.gif";
|
||||
[self.animatedImageInterface sd_setImageWithURL:[NSURL URLWithString:urlString3] placeholderImage:nil options:SDWebImageProgressiveLoad context:@{SDWebImageContextAnimatedImageClass : SDAnimatedImage.class} progress:nil completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
|
||||
if (![image isKindOfClass:[SDAnimatedImage class]]) {
|
||||
return;
|
||||
}
|
||||
__weak typeof(self) wself = self;
|
||||
self.player = [SDAnimatedImagePlayer playerWithProvider:(SDAnimatedImage *)image];
|
||||
self.player.animationFrameHandler = ^(NSUInteger index, UIImage * _Nonnull frame) {
|
||||
[wself.animatedImageInterface setImage:frame];
|
||||
};
|
||||
[self.player startPlaying];
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)clearCache {
|
||||
[SDImageCache.sharedImageCache clearMemory];
|
||||
[SDImageCache.sharedImageCache clearDiskOnCompletion:nil];
|
||||
}
|
||||
|
||||
- (void)didDeactivate {
|
||||
|
|
|
@ -1,12 +1,10 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<document type="com.apple.InterfaceBuilder.WatchKit.Storyboard" version="3.0" toolsVersion="14490.70" targetRuntime="watchKit" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="AgC-eL-Hgc">
|
||||
<device id="watch38" orientation="portrait">
|
||||
<adaptation id="fullscreen"/>
|
||||
</device>
|
||||
<document type="com.apple.InterfaceBuilder.WatchKit.Storyboard" version="3.0" toolsVersion="15505" targetRuntime="watchKit" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="AgC-eL-Hgc">
|
||||
<device id="watch38"/>
|
||||
<dependencies>
|
||||
<deployment identifier="watchOS"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14490.49"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBWatchKitPlugin" version="14490.21"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="15509"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBWatchKitPlugin" version="15501"/>
|
||||
</dependencies>
|
||||
<scenes>
|
||||
<!--Interface Controller-->
|
||||
|
@ -14,10 +12,14 @@
|
|||
<objects>
|
||||
<controller id="AgC-eL-Hgc" customClass="InterfaceController">
|
||||
<items>
|
||||
<imageView height="150" alignment="left" id="tBV-Mv-OtJ"/>
|
||||
<imageView alignment="left" contentMode="scaleAspectFit" id="Tox-Rh-1mN"/>
|
||||
<imageView alignment="left" contentMode="scaleAspectFit" id="tBV-Mv-OtJ"/>
|
||||
<imageView alignment="left" contentMode="scaleAspectFit" id="7dg-wI-usi"/>
|
||||
</items>
|
||||
<connections>
|
||||
<outlet property="imageInterface" destination="tBV-Mv-OtJ" id="uId-u2-it3"/>
|
||||
<outlet property="animatedImageInterface" destination="7dg-wI-usi" id="eDq-ra-x9k"/>
|
||||
<outlet property="simpleAnimatedImageInterface" destination="tBV-Mv-OtJ" id="Wzc-db-ghd"/>
|
||||
<outlet property="staticImageInterface" destination="Tox-Rh-1mN" id="M4p-h5-1ld"/>
|
||||
</connections>
|
||||
</controller>
|
||||
</objects>
|
||||
|
|
|
@ -89,6 +89,13 @@
|
|||
325C46272233A0A8004CAE11 /* NSBezierPath+RoundedCorners.h in Headers */ = {isa = PBXBuildFile; fileRef = 325C46242233A0A8004CAE11 /* NSBezierPath+RoundedCorners.h */; settings = {ATTRIBUTES = (Private, ); }; };
|
||||
325C46282233A0A8004CAE11 /* NSBezierPath+RoundedCorners.m in Sources */ = {isa = PBXBuildFile; fileRef = 325C46252233A0A8004CAE11 /* NSBezierPath+RoundedCorners.m */; };
|
||||
325C46292233A0A8004CAE11 /* NSBezierPath+RoundedCorners.m in Sources */ = {isa = PBXBuildFile; fileRef = 325C46252233A0A8004CAE11 /* NSBezierPath+RoundedCorners.m */; };
|
||||
326E2F2E236F0B23006F847F /* SDAnimatedImagePlayer.h in Headers */ = {isa = PBXBuildFile; fileRef = 326E2F2C236F0B23006F847F /* SDAnimatedImagePlayer.h */; settings = {ATTRIBUTES = (Public, ); }; };
|
||||
326E2F2F236F0B23006F847F /* SDAnimatedImagePlayer.m in Sources */ = {isa = PBXBuildFile; fileRef = 326E2F2D236F0B23006F847F /* SDAnimatedImagePlayer.m */; };
|
||||
326E2F30236F0B23006F847F /* SDAnimatedImagePlayer.m in Sources */ = {isa = PBXBuildFile; fileRef = 326E2F2D236F0B23006F847F /* SDAnimatedImagePlayer.m */; };
|
||||
326E2F33236F1D58006F847F /* SDDeviceHelper.h in Headers */ = {isa = PBXBuildFile; fileRef = 326E2F31236F1D58006F847F /* SDDeviceHelper.h */; settings = {ATTRIBUTES = (Private, ); }; };
|
||||
326E2F34236F1D58006F847F /* SDDeviceHelper.m in Sources */ = {isa = PBXBuildFile; fileRef = 326E2F32236F1D58006F847F /* SDDeviceHelper.m */; };
|
||||
326E2F35236F1D58006F847F /* SDDeviceHelper.m in Sources */ = {isa = PBXBuildFile; fileRef = 326E2F32236F1D58006F847F /* SDDeviceHelper.m */; };
|
||||
326E2F36236F1E30006F847F /* SDAnimatedImagePlayer.h in Copy Headers */ = {isa = PBXBuildFile; fileRef = 326E2F2C236F0B23006F847F /* SDAnimatedImagePlayer.h */; };
|
||||
327054D6206CD8B3006EA328 /* SDImageAPNGCoder.h in Headers */ = {isa = PBXBuildFile; fileRef = 327054D2206CD8B3006EA328 /* SDImageAPNGCoder.h */; settings = {ATTRIBUTES = (Public, ); }; };
|
||||
327054DA206CD8B3006EA328 /* SDImageAPNGCoder.m in Sources */ = {isa = PBXBuildFile; fileRef = 327054D3206CD8B3006EA328 /* SDImageAPNGCoder.m */; };
|
||||
327054DC206CD8B3006EA328 /* SDImageAPNGCoder.m in Sources */ = {isa = PBXBuildFile; fileRef = 327054D3206CD8B3006EA328 /* SDImageAPNGCoder.m */; };
|
||||
|
@ -291,6 +298,7 @@
|
|||
dstPath = include/SDWebImage;
|
||||
dstSubfolderSpec = 16;
|
||||
files = (
|
||||
326E2F36236F1E30006F847F /* SDAnimatedImagePlayer.h in Copy Headers */,
|
||||
3250C9F12355E3DF0093A896 /* SDWebImageDownloaderDecryptor.h in Copy Headers */,
|
||||
325427662355783C0042BAA4 /* SDWebImageDownloaderResponseModifier.h in Copy Headers */,
|
||||
3298655F233723220071958B /* SDImageHEICCoder.h in Copy Headers */,
|
||||
|
@ -399,6 +407,10 @@
|
|||
325C461F2233A02E004CAE11 /* UIColor+HexString.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "UIColor+HexString.m"; sourceTree = "<group>"; };
|
||||
325C46242233A0A8004CAE11 /* NSBezierPath+RoundedCorners.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "NSBezierPath+RoundedCorners.h"; sourceTree = "<group>"; };
|
||||
325C46252233A0A8004CAE11 /* NSBezierPath+RoundedCorners.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "NSBezierPath+RoundedCorners.m"; sourceTree = "<group>"; };
|
||||
326E2F2C236F0B23006F847F /* SDAnimatedImagePlayer.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = SDAnimatedImagePlayer.h; path = Core/SDAnimatedImagePlayer.h; sourceTree = "<group>"; };
|
||||
326E2F2D236F0B23006F847F /* SDAnimatedImagePlayer.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = SDAnimatedImagePlayer.m; path = Core/SDAnimatedImagePlayer.m; sourceTree = "<group>"; };
|
||||
326E2F31236F1D58006F847F /* SDDeviceHelper.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SDDeviceHelper.h; sourceTree = "<group>"; };
|
||||
326E2F32236F1D58006F847F /* SDDeviceHelper.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SDDeviceHelper.m; sourceTree = "<group>"; };
|
||||
327054D2206CD8B3006EA328 /* SDImageAPNGCoder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SDImageAPNGCoder.h; path = Core/SDImageAPNGCoder.h; sourceTree = "<group>"; };
|
||||
327054D3206CD8B3006EA328 /* SDImageAPNGCoder.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SDImageAPNGCoder.m; path = Core/SDImageAPNGCoder.m; sourceTree = "<group>"; };
|
||||
328BB69A2081FED200760D6C /* SDWebImageCacheKeyFilter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = SDWebImageCacheKeyFilter.h; path = Core/SDWebImageCacheKeyFilter.h; sourceTree = "<group>"; };
|
||||
|
@ -563,6 +575,8 @@
|
|||
3248475C201775F600AF9E5A /* SDAnimatedImageView+WebCache.m */,
|
||||
320224B9203979BA00E9F285 /* SDAnimatedImageRep.h */,
|
||||
320224BA203979BA00E9F285 /* SDAnimatedImageRep.m */,
|
||||
326E2F2C236F0B23006F847F /* SDAnimatedImagePlayer.h */,
|
||||
326E2F2D236F0B23006F847F /* SDAnimatedImagePlayer.m */,
|
||||
);
|
||||
name = AnimatedImage;
|
||||
sourceTree = "<group>";
|
||||
|
@ -609,6 +623,8 @@
|
|||
325C460722339426004CAE11 /* SDWeakProxy.m */,
|
||||
32E6730F235765B500DB4987 /* SDDisplayLink.h */,
|
||||
32E67310235765B500DB4987 /* SDDisplayLink.m */,
|
||||
326E2F31236F1D58006F847F /* SDDeviceHelper.h */,
|
||||
326E2F32236F1D58006F847F /* SDDeviceHelper.m */,
|
||||
325C460022339330004CAE11 /* SDImageAssetManager.h */,
|
||||
325C460122339330004CAE11 /* SDImageAssetManager.m */,
|
||||
325C460C223394D8004CAE11 /* SDImageCachesManagerOperation.h */,
|
||||
|
@ -846,9 +862,11 @@
|
|||
80B6DF842142B44600BCB334 /* NSButton+WebCache.h in Headers */,
|
||||
43A918661D8308FE00B3925F /* SDImageCacheConfig.h in Headers */,
|
||||
3290FA061FA478AF0047D20C /* SDImageFrame.h in Headers */,
|
||||
326E2F33236F1D58006F847F /* SDDeviceHelper.h in Headers */,
|
||||
329F1237223FAA3B00B309FD /* SDmetamacros.h in Headers */,
|
||||
324DF4B6200A14DC008A84CC /* SDWebImageDefine.h in Headers */,
|
||||
32A09E3F233358B700339F9D /* SDImageIOAnimatedCoder.h in Headers */,
|
||||
326E2F2E236F0B23006F847F /* SDAnimatedImagePlayer.h in Headers */,
|
||||
807A122A1F89636300EC2A9B /* SDImageCodersManager.h in Headers */,
|
||||
3244062C2296C5F400A36084 /* SDWebImageOptionsProcessor.h in Headers */,
|
||||
4A2CAE211AB4BB7000B6BC39 /* SDWebImageManager.h in Headers */,
|
||||
|
@ -1086,6 +1104,7 @@
|
|||
328BB6A42081FED200760D6C /* SDWebImageCacheKeyFilter.m in Sources */,
|
||||
32E67313235765B500DB4987 /* SDDisplayLink.m in Sources */,
|
||||
4A2CAE2E1AB4BB7500B6BC39 /* UIImage+GIF.m in Sources */,
|
||||
326E2F35236F1D58006F847F /* SDDeviceHelper.m in Sources */,
|
||||
80B6DF822142B44400BCB334 /* NSButton+WebCache.m in Sources */,
|
||||
32D3CDCF21DDE87300C4DB49 /* UIImage+MemoryCacheCost.m in Sources */,
|
||||
329F1241223FAD3400B309FD /* SDInternalMacros.m in Sources */,
|
||||
|
@ -1119,6 +1138,7 @@
|
|||
321E608E1F38E8C800405457 /* SDImageCoder.m in Sources */,
|
||||
4A2CAE301AB4BB7500B6BC39 /* UIImage+MultiFormat.m in Sources */,
|
||||
4A2CAE1C1AB4BB6800B6BC39 /* SDWebImageDownloader.m in Sources */,
|
||||
326E2F30236F0B23006F847F /* SDAnimatedImagePlayer.m in Sources */,
|
||||
4A2CAE2A1AB4BB7500B6BC39 /* NSData+ImageContentType.m in Sources */,
|
||||
4A2CAE221AB4BB7000B6BC39 /* SDWebImageManager.m in Sources */,
|
||||
4A2CAE191AB4BB6400B6BC39 /* SDWebImageCompat.m in Sources */,
|
||||
|
@ -1154,6 +1174,7 @@
|
|||
328BB6A22081FED200760D6C /* SDWebImageCacheKeyFilter.m in Sources */,
|
||||
32E67312235765B500DB4987 /* SDDisplayLink.m in Sources */,
|
||||
53761309155AD0D5005750A4 /* SDImageCache.m in Sources */,
|
||||
326E2F34236F1D58006F847F /* SDDeviceHelper.m in Sources */,
|
||||
80B6DF832142B44500BCB334 /* NSButton+WebCache.m in Sources */,
|
||||
32D3CDCE21DDE87300C4DB49 /* UIImage+MemoryCacheCost.m in Sources */,
|
||||
329F1240223FAD3400B309FD /* SDInternalMacros.m in Sources */,
|
||||
|
@ -1187,6 +1208,7 @@
|
|||
321E608C1F38E8C800405457 /* SDImageCoder.m in Sources */,
|
||||
5376130E155AD0D5005750A4 /* UIButton+WebCache.m in Sources */,
|
||||
5376130F155AD0D5005750A4 /* UIImageView+WebCache.m in Sources */,
|
||||
326E2F2F236F0B23006F847F /* SDAnimatedImagePlayer.m in Sources */,
|
||||
530E49EC16464C84002868E7 /* SDWebImageDownloaderOperation.m in Sources */,
|
||||
53406750167780C40042B59E /* SDWebImageCompat.m in Sources */,
|
||||
321B37872083290E00C0EA77 /* SDImageLoader.m in Sources */,
|
||||
|
|
|
@ -57,6 +57,12 @@
|
|||
*/
|
||||
@property (nonatomic, assign, readonly, getter=isAllFramesLoaded) BOOL allFramesLoaded;
|
||||
|
||||
/**
|
||||
Return the animated image coder if the image is created with `initWithAnimatedCoder:scale:` method.
|
||||
@note We use this with animated coder which conforms to `SDProgressiveImageCoder` for progressive animation decoding.
|
||||
*/
|
||||
@property (nonatomic, strong, readonly, nullable) id<SDAnimatedImageCoder> animatedCoder;
|
||||
|
||||
@end
|
||||
|
||||
/**
|
||||
|
|
|
@ -32,7 +32,7 @@ static CGFloat SDImageScaleFromPath(NSString *string) {
|
|||
|
||||
@interface SDAnimatedImage ()
|
||||
|
||||
@property (nonatomic, strong) id<SDAnimatedImageCoder> coder;
|
||||
@property (nonatomic, strong) id<SDAnimatedImageCoder> animatedCoder;
|
||||
@property (nonatomic, assign, readwrite) SDImageFormat animatedImageFormat;
|
||||
@property (atomic, copy) NSArray<SDImageFrame *> *loadedAnimatedImageFrames; // Mark as atomic to keep thread-safe
|
||||
@property (nonatomic, assign, getter=isAllFramesLoaded) BOOL allFramesLoaded;
|
||||
|
@ -156,7 +156,7 @@ static CGFloat SDImageScaleFromPath(NSString *string) {
|
|||
self = [super initWithCGImage:image.CGImage scale:MAX(scale, 1) orientation:image.imageOrientation];
|
||||
#endif
|
||||
if (self) {
|
||||
_coder = animatedCoder;
|
||||
_animatedCoder = animatedCoder;
|
||||
NSData *data = [animatedCoder animatedImageData];
|
||||
SDImageFormat format = [NSData sd_imageFormatForImageData:data];
|
||||
_animatedImageFormat = format;
|
||||
|
@ -207,7 +207,7 @@ static CGFloat SDImageScaleFromPath(NSString *string) {
|
|||
if (!animatedCoder) {
|
||||
return self;
|
||||
}
|
||||
_coder = animatedCoder;
|
||||
_animatedCoder = animatedCoder;
|
||||
SDImageFormat format = [NSData sd_imageFormatForImageData:animatedImageData];
|
||||
_animatedImageFormat = format;
|
||||
}
|
||||
|
@ -229,15 +229,15 @@ static CGFloat SDImageScaleFromPath(NSString *string) {
|
|||
#pragma mark - SDAnimatedImage
|
||||
|
||||
- (NSData *)animatedImageData {
|
||||
return [self.coder animatedImageData];
|
||||
return [self.animatedCoder animatedImageData];
|
||||
}
|
||||
|
||||
- (NSUInteger)animatedImageLoopCount {
|
||||
return [self.coder animatedImageLoopCount];
|
||||
return [self.animatedCoder animatedImageLoopCount];
|
||||
}
|
||||
|
||||
- (NSUInteger)animatedImageFrameCount {
|
||||
return [self.coder animatedImageFrameCount];
|
||||
return [self.animatedCoder animatedImageFrameCount];
|
||||
}
|
||||
|
||||
- (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index {
|
||||
|
@ -248,7 +248,7 @@ static CGFloat SDImageScaleFromPath(NSString *string) {
|
|||
SDImageFrame *frame = [self.loadedAnimatedImageFrames objectAtIndex:index];
|
||||
return frame.image;
|
||||
}
|
||||
return [self.coder animatedImageFrameAtIndex:index];
|
||||
return [self.animatedCoder animatedImageFrameAtIndex:index];
|
||||
}
|
||||
|
||||
- (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index {
|
||||
|
@ -259,7 +259,7 @@ static CGFloat SDImageScaleFromPath(NSString *string) {
|
|||
SDImageFrame *frame = [self.loadedAnimatedImageFrames objectAtIndex:index];
|
||||
return frame.duration;
|
||||
}
|
||||
return [self.coder animatedImageDurationAtIndex:index];
|
||||
return [self.animatedCoder animatedImageDurationAtIndex:index];
|
||||
}
|
||||
|
||||
@end
|
||||
|
|
|
@ -0,0 +1,82 @@
|
|||
/*
|
||||
* This file is part of the SDWebImage package.
|
||||
* (c) Olivier Poitrey <rs@dailymotion.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SDWebImageCompat.h"
|
||||
#import "SDImageCoder.h"
|
||||
|
||||
/// A player to control the playback of animated image, which can be used to drive Animated ImageView or any rendering usage, like CALayer/WatchKit/SwiftUI rendering.
|
||||
@interface SDAnimatedImagePlayer : NSObject
|
||||
|
||||
/// Current playing frame image. This value is KVO Compliance.
|
||||
@property (nonatomic, readonly, nullable) UIImage *currentFrame;
|
||||
|
||||
/// Current frame index, zero based. This value is KVO Compliance.
|
||||
@property (nonatomic, readonly) NSUInteger currentFrameIndex;
|
||||
|
||||
/// Current loop count since its latest animating. This value is KVO Compliance.
|
||||
@property (nonatomic, readonly) NSUInteger currentLoopCount;
|
||||
|
||||
/// Total frame count for niamted image rendering. Defaults is animated image's frame count.
|
||||
/// @note For progressive animation, you can update this value when your provider receive more frames.
|
||||
@property (nonatomic, assign) NSUInteger totalFrameCount;
|
||||
|
||||
/// Total loop count for animated image rendering. Default is animated image's loop count.
|
||||
@property (nonatomic, assign) NSUInteger totalLoopCount;
|
||||
|
||||
/// Provide a max buffer size by bytes. This is used to adjust frame buffer count and can be useful when the decoding cost is expensive (such as Animated WebP software decoding). Default is 0.
|
||||
/// `0` means automatically adjust by calculating current memory usage.
|
||||
/// `1` means without any buffer cache, each of frames will be decoded and then be freed after rendering. (Lowest Memory and Highest CPU)
|
||||
/// `NSUIntegerMax` means cache all the buffer. (Lowest CPU and Highest Memory)
|
||||
@property (nonatomic, assign) NSUInteger maxBufferSize;
|
||||
|
||||
/// You can specify a runloop mode to let it rendering.
|
||||
/// Default is NSRunLoopCommonModes on multi-core device, NSDefaultRunLoopMode on single-core device
|
||||
@property (nonatomic, copy, nonnull) NSRunLoopMode runLoopMode;
|
||||
|
||||
/// Create a player with animated image provider. If the provider's `animatedImageFrameCount` is less than 1, returns nil.
|
||||
/// The provider can be any protocol implementation, like `SDAnimatedImage`, `SDImageGIFCoder`, etc.
|
||||
/// @note This provider can represent mutable content, like prorgessive animated loading. But you need to update the frame count by yourself
|
||||
/// @param provider The animated provider
|
||||
- (nullable instancetype)initWithProvider:(nonnull id<SDAnimatedImageProvider>)provider;
|
||||
|
||||
/// Create a player with animated image provider. If the provider's `animatedImageFrameCount` is less than 1, returns nil.
|
||||
/// The provider can be any protocol implementation, like `SDAnimatedImage` or `SDImageGIFCoder`, etc.
|
||||
/// @note This provider can represent mutable content, like prorgessive animated loading. But you need to update the frame count by yourself
|
||||
/// @param provider The animated provider
|
||||
+ (nullable instancetype)playerWithProvider:(nonnull id<SDAnimatedImageProvider>)provider;
|
||||
|
||||
/// The handler block when current frame and index changed.
|
||||
@property (nonatomic, copy, nullable) void (^animationFrameHandler)(NSUInteger index, UIImage * _Nonnull frame);
|
||||
|
||||
/// The handler block when one loop count finished.
|
||||
@property (nonatomic, copy, nullable) void (^animationLoopHandler)(NSUInteger loopCount);
|
||||
|
||||
/// Return the status whehther animation is playing.
|
||||
@property (nonatomic, readonly) BOOL isPlaying;
|
||||
|
||||
/// Start the animation. Or resume the previously paused animation.
|
||||
- (void)startPlaying;
|
||||
|
||||
/// Pause the aniamtion. Keep the current frame index and loop count.
|
||||
- (void)pausePlaying;
|
||||
|
||||
/// Stop the animation. Reset the current frame index and loop count.
|
||||
- (void)stopPlaying;
|
||||
|
||||
/// Seek to the desired frame index and loop count.
|
||||
/// @note This can be used for advanced control like progressive loading, or skipping specify frames.
|
||||
/// @param index The frame index
|
||||
/// @param loopCount The loop count
|
||||
- (void)seekToFrameAtIndex:(NSUInteger)index loopCount:(NSUInteger)loopCount;
|
||||
|
||||
/// Clear the frame cache buffer. The frame cache buffer size can be controled by `maxBufferSize`.
|
||||
/// By default, when stop or pause the animation, the frame buffer is still kept to ready for the next restart
|
||||
- (void)clearFrameBuffer;
|
||||
|
||||
@end
|
|
@ -0,0 +1,365 @@
|
|||
/*
|
||||
* This file is part of the SDWebImage package.
|
||||
* (c) Olivier Poitrey <rs@dailymotion.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
#import "SDAnimatedImagePlayer.h"
|
||||
#import "NSImage+Compatibility.h"
|
||||
#import "SDDisplayLink.h"
|
||||
#import "SDDeviceHelper.h"
|
||||
#import "SDInternalMacros.h"
|
||||
|
||||
@interface SDAnimatedImagePlayer () {
|
||||
NSRunLoopMode _runLoopMode;
|
||||
}
|
||||
|
||||
@property (nonatomic, strong, readwrite) UIImage *currentFrame;
|
||||
@property (nonatomic, assign, readwrite) NSUInteger currentFrameIndex;
|
||||
@property (nonatomic, assign, readwrite) NSUInteger currentLoopCount;
|
||||
@property (nonatomic, strong) id<SDAnimatedImageProvider> animatedProvider;
|
||||
@property (nonatomic, strong) NSMutableDictionary<NSNumber *, UIImage *> *frameBuffer;
|
||||
@property (nonatomic, assign) NSTimeInterval currentTime;
|
||||
@property (nonatomic, assign) BOOL bufferMiss;
|
||||
@property (nonatomic, assign) NSUInteger maxBufferCount;
|
||||
@property (nonatomic, strong) NSOperationQueue *fetchQueue;
|
||||
@property (nonatomic, strong) dispatch_semaphore_t lock;
|
||||
@property (nonatomic, strong) SDDisplayLink *displayLink;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SDAnimatedImagePlayer
|
||||
|
||||
- (instancetype)initWithProvider:(id<SDAnimatedImageProvider>)provider {
|
||||
self = [super init];
|
||||
if (self) {
|
||||
NSUInteger animatedImageFrameCount = provider.animatedImageFrameCount;
|
||||
// Check the frame count
|
||||
if (animatedImageFrameCount <= 1) {
|
||||
return nil;
|
||||
}
|
||||
self.totalFrameCount = animatedImageFrameCount;
|
||||
// Get the current frame and loop count.
|
||||
self.totalLoopCount = provider.animatedImageLoopCount;
|
||||
self.animatedProvider = provider;
|
||||
#if SD_UIKIT
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
|
||||
#endif
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
+ (instancetype)playerWithProvider:(id<SDAnimatedImageProvider>)provider {
|
||||
SDAnimatedImagePlayer *player = [[SDAnimatedImagePlayer alloc] initWithProvider:provider];
|
||||
return player;
|
||||
}
|
||||
|
||||
#pragma mark - Life Cycle
|
||||
|
||||
- (void)dealloc {
|
||||
#if SD_UIKIT
|
||||
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
|
||||
#endif
|
||||
}
|
||||
|
||||
- (void)didReceiveMemoryWarning:(NSNotification *)notification {
|
||||
[_fetchQueue cancelAllOperations];
|
||||
[_fetchQueue addOperationWithBlock:^{
|
||||
NSNumber *currentFrameIndex = @(self.currentFrameIndex);
|
||||
SD_LOCK(self.lock);
|
||||
NSArray *keys = self.frameBuffer.allKeys;
|
||||
// only keep the next frame for later rendering
|
||||
for (NSNumber * key in keys) {
|
||||
if (![key isEqualToNumber:currentFrameIndex]) {
|
||||
[self.frameBuffer removeObjectForKey:key];
|
||||
}
|
||||
}
|
||||
SD_UNLOCK(self.lock);
|
||||
}];
|
||||
}
|
||||
|
||||
#pragma mark - Private
|
||||
- (NSOperationQueue *)fetchQueue {
|
||||
if (!_fetchQueue) {
|
||||
_fetchQueue = [[NSOperationQueue alloc] init];
|
||||
_fetchQueue.maxConcurrentOperationCount = 1;
|
||||
}
|
||||
return _fetchQueue;
|
||||
}
|
||||
|
||||
- (NSMutableDictionary<NSNumber *,UIImage *> *)frameBuffer {
|
||||
if (!_frameBuffer) {
|
||||
_frameBuffer = [NSMutableDictionary dictionary];
|
||||
}
|
||||
return _frameBuffer;
|
||||
}
|
||||
|
||||
- (dispatch_semaphore_t)lock {
|
||||
if (!_lock) {
|
||||
_lock = dispatch_semaphore_create(1);
|
||||
}
|
||||
return _lock;
|
||||
}
|
||||
|
||||
- (SDDisplayLink *)displayLink {
|
||||
if (!_displayLink) {
|
||||
_displayLink = [SDDisplayLink displayLinkWithTarget:self selector:@selector(displayDidRefresh:)];
|
||||
[_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:self.runLoopMode];
|
||||
}
|
||||
return _displayLink;
|
||||
}
|
||||
|
||||
- (void)setRunLoopMode:(NSRunLoopMode)runLoopMode {
|
||||
if ([_runLoopMode isEqual:runLoopMode]) {
|
||||
return;
|
||||
}
|
||||
if (_displayLink) {
|
||||
if (_runLoopMode) {
|
||||
[_displayLink removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:_runLoopMode];
|
||||
}
|
||||
if (runLoopMode.length > 0) {
|
||||
[_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:runLoopMode];
|
||||
}
|
||||
}
|
||||
_runLoopMode = [runLoopMode copy];
|
||||
}
|
||||
|
||||
- (NSRunLoopMode)runLoopMode {
|
||||
if (!_runLoopMode) {
|
||||
_runLoopMode = [[self class] defaultRunLoopMode];
|
||||
}
|
||||
return _runLoopMode;
|
||||
}
|
||||
|
||||
#pragma mark - State Control
|
||||
|
||||
- (void)setupCurrentFrame {
|
||||
if (self.currentFrameIndex != 0) {
|
||||
return;
|
||||
}
|
||||
if ([self.animatedProvider isKindOfClass:[UIImage class]]) {
|
||||
UIImage *image = (UIImage *)self.animatedProvider;
|
||||
// Use the poster image if available
|
||||
#if SD_MAC
|
||||
UIImage *posterFrame = [[NSImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:kCGImagePropertyOrientationUp];
|
||||
#else
|
||||
UIImage *posterFrame = [[UIImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:image.imageOrientation];
|
||||
#endif
|
||||
if (posterFrame) {
|
||||
self.currentFrame = posterFrame;
|
||||
SD_LOCK(self.lock);
|
||||
self.frameBuffer[@(self.currentFrameIndex)] = self.currentFrame;
|
||||
SD_UNLOCK(self.lock);
|
||||
[self handleFrameChange];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)resetCurrentFrameIndex {
|
||||
self.currentFrame = nil;
|
||||
self.currentFrameIndex = 0;
|
||||
self.currentLoopCount = 0;
|
||||
self.currentTime = 0;
|
||||
self.bufferMiss = NO;
|
||||
[self handleFrameChange];
|
||||
}
|
||||
|
||||
- (void)clearFrameBuffer {
|
||||
SD_LOCK(self.lock);
|
||||
[_frameBuffer removeAllObjects];
|
||||
SD_UNLOCK(self.lock);
|
||||
}
|
||||
|
||||
#pragma mark - Animation Control
|
||||
- (void)startPlaying {
|
||||
[self.displayLink start];
|
||||
// Calculate max buffer size
|
||||
[self calculateMaxBufferCount];
|
||||
// Setup frame
|
||||
if (self.currentFrameIndex == 0 && !self.currentFrame) {
|
||||
[self setupCurrentFrame];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)stopPlaying {
|
||||
[_fetchQueue cancelAllOperations];
|
||||
// Using `_displayLink` here because when UIImageView dealloc, it may trigger `[self stopAnimating]`, we already release the display link in SDAnimatedImageView's dealloc method.
|
||||
[_displayLink stop];
|
||||
[self resetCurrentFrameIndex];
|
||||
}
|
||||
|
||||
- (void)pausePlaying {
|
||||
[_fetchQueue cancelAllOperations];
|
||||
[_displayLink stop];
|
||||
}
|
||||
|
||||
- (BOOL)isPlaying {
|
||||
return self.displayLink.isRunning;
|
||||
}
|
||||
|
||||
- (void)seekToFrameAtIndex:(NSUInteger)index loopCount:(NSUInteger)loopCount {
|
||||
if (index >= self.totalFrameCount) {
|
||||
return;
|
||||
}
|
||||
self.currentFrameIndex = index;
|
||||
self.currentLoopCount = loopCount;
|
||||
[self handleFrameChange];
|
||||
}
|
||||
|
||||
#pragma mark - Core Render
|
||||
- (void)displayDidRefresh:(SDDisplayLink *)displayLink {
|
||||
// If for some reason a wild call makes it through when we shouldn't be animating, bail.
|
||||
// Early return!
|
||||
if (!self.isPlaying) {
|
||||
return;
|
||||
}
|
||||
// Calculate refresh duration
|
||||
NSTimeInterval duration = self.displayLink.duration;
|
||||
|
||||
NSUInteger totalFrameCount = self.totalFrameCount;
|
||||
if (totalFrameCount <= 1) {
|
||||
// Total frame count less than 1, wrong configuration and stop animating
|
||||
[self stopPlaying];
|
||||
return;
|
||||
}
|
||||
NSUInteger currentFrameIndex = self.currentFrameIndex;
|
||||
NSUInteger nextFrameIndex = (currentFrameIndex + 1) % totalFrameCount;
|
||||
|
||||
// Check if we have the frame buffer firstly to improve performance
|
||||
if (!self.bufferMiss) {
|
||||
// Then check if timestamp is reached
|
||||
self.currentTime += duration;
|
||||
NSTimeInterval currentDuration = [self.animatedProvider animatedImageDurationAtIndex:currentFrameIndex];
|
||||
if (self.currentTime < currentDuration) {
|
||||
// Current frame timestamp not reached, return
|
||||
return;
|
||||
}
|
||||
self.currentTime -= currentDuration;
|
||||
NSTimeInterval nextDuration = [self.animatedProvider animatedImageDurationAtIndex:nextFrameIndex];
|
||||
if (self.currentTime > nextDuration) {
|
||||
// Do not skip frame
|
||||
self.currentTime = nextDuration;
|
||||
}
|
||||
}
|
||||
|
||||
// Update the current frame
|
||||
UIImage *currentFrame;
|
||||
UIImage *fetchFrame;
|
||||
SD_LOCK(self.lock);
|
||||
currentFrame = self.frameBuffer[@(currentFrameIndex)];
|
||||
fetchFrame = currentFrame ? self.frameBuffer[@(nextFrameIndex)] : nil;
|
||||
SD_UNLOCK(self.lock);
|
||||
BOOL bufferFull = NO;
|
||||
if (currentFrame) {
|
||||
SD_LOCK(self.lock);
|
||||
// Remove the frame buffer if need
|
||||
if (self.frameBuffer.count > self.maxBufferCount) {
|
||||
self.frameBuffer[@(currentFrameIndex)] = nil;
|
||||
}
|
||||
// Check whether we can stop fetch
|
||||
if (self.frameBuffer.count == totalFrameCount) {
|
||||
bufferFull = YES;
|
||||
}
|
||||
SD_UNLOCK(self.lock);
|
||||
self.currentFrame = currentFrame;
|
||||
[self handleFrameChange];
|
||||
self.currentFrameIndex = nextFrameIndex;
|
||||
self.bufferMiss = NO;
|
||||
} else {
|
||||
self.bufferMiss = YES;
|
||||
}
|
||||
|
||||
// Update the loop count when last frame rendered
|
||||
if (nextFrameIndex == 0 && !self.bufferMiss) {
|
||||
// Update the loop count
|
||||
self.currentLoopCount++;
|
||||
[self handleLoopChnage];
|
||||
// if reached the max loop count, stop animating, 0 means loop indefinitely
|
||||
NSUInteger maxLoopCount = self.totalLoopCount;
|
||||
if (maxLoopCount != 0 && (self.currentLoopCount >= maxLoopCount)) {
|
||||
[self stopPlaying];
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Since we support handler, check animating state again
|
||||
if (!self.isPlaying) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if we should prefetch next frame or current frame
|
||||
NSUInteger fetchFrameIndex;
|
||||
if (self.bufferMiss) {
|
||||
// When buffer miss, means the decode speed is slower than render speed, we fetch current miss frame
|
||||
fetchFrameIndex = currentFrameIndex;
|
||||
} else {
|
||||
// Or, most cases, the decode speed is faster than render speed, we fetch next frame
|
||||
fetchFrameIndex = nextFrameIndex;
|
||||
}
|
||||
|
||||
if (!fetchFrame && !bufferFull && self.fetchQueue.operationCount == 0) {
|
||||
// Prefetch next frame in background queue
|
||||
id<SDAnimatedImageProvider> animatedProvider = self.animatedProvider;
|
||||
@weakify(self);
|
||||
NSOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
|
||||
@strongify(self);
|
||||
if (!self) {
|
||||
return;
|
||||
}
|
||||
UIImage *frame = [animatedProvider animatedImageFrameAtIndex:fetchFrameIndex];
|
||||
|
||||
BOOL isAnimating = self.displayLink.isRunning;
|
||||
if (isAnimating) {
|
||||
SD_LOCK(self.lock);
|
||||
self.frameBuffer[@(fetchFrameIndex)] = frame;
|
||||
SD_UNLOCK(self.lock);
|
||||
}
|
||||
}];
|
||||
[self.fetchQueue addOperation:operation];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)handleFrameChange {
|
||||
if (self.animationFrameHandler) {
|
||||
self.animationFrameHandler(self.currentFrameIndex, self.currentFrame);
|
||||
}
|
||||
}
|
||||
|
||||
- (void)handleLoopChnage {
|
||||
if (self.animationLoopHandler) {
|
||||
self.animationLoopHandler(self.currentLoopCount);
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - Util
|
||||
- (void)calculateMaxBufferCount {
|
||||
NSUInteger bytes = CGImageGetBytesPerRow(self.currentFrame.CGImage) * CGImageGetHeight(self.currentFrame.CGImage);
|
||||
if (bytes == 0) bytes = 1024;
|
||||
|
||||
NSUInteger max = 0;
|
||||
if (self.maxBufferSize > 0) {
|
||||
max = self.maxBufferSize;
|
||||
} else {
|
||||
// Calculate based on current memory, these factors are by experience
|
||||
NSUInteger total = [SDDeviceHelper totalMemory];
|
||||
NSUInteger free = [SDDeviceHelper freeMemory];
|
||||
max = MIN(total * 0.2, free * 0.6);
|
||||
}
|
||||
|
||||
NSUInteger maxBufferCount = (double)max / (double)bytes;
|
||||
if (!maxBufferCount) {
|
||||
// At least 1 frame
|
||||
maxBufferCount = 1;
|
||||
}
|
||||
|
||||
self.maxBufferCount = maxBufferCount;
|
||||
}
|
||||
|
||||
+ (NSString *)defaultRunLoopMode {
|
||||
// Key off `activeProcessorCount` (as opposed to `processorCount`) since the system could shut down cores in certain situations.
|
||||
return [NSProcessInfo processInfo].activeProcessorCount > 1 ? NSRunLoopCommonModes : NSDefaultRunLoopMode;
|
||||
}
|
||||
|
||||
@end
|
|
@ -21,7 +21,7 @@
|
|||
@interface SDAnimatedImageView : UIImageView
|
||||
|
||||
/**
|
||||
Current display frame image.
|
||||
Current display frame image. This value is KVO Compliance.
|
||||
*/
|
||||
@property (nonatomic, strong, readonly, nullable) UIImage *currentFrame;
|
||||
/**
|
||||
|
|
|
@ -10,52 +10,22 @@
|
|||
|
||||
#if SD_UIKIT || SD_MAC
|
||||
|
||||
#import "SDAnimatedImagePlayer.h"
|
||||
#import "UIImage+Metadata.h"
|
||||
#import "NSImage+Compatibility.h"
|
||||
#import "SDDisplayLink.h"
|
||||
#import "SDInternalMacros.h"
|
||||
#import <mach/mach.h>
|
||||
#import <objc/runtime.h>
|
||||
|
||||
static NSUInteger SDDeviceTotalMemory() {
|
||||
return (NSUInteger)[[NSProcessInfo processInfo] physicalMemory];
|
||||
}
|
||||
|
||||
static NSUInteger SDDeviceFreeMemory() {
|
||||
mach_port_t host_port = mach_host_self();
|
||||
mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
|
||||
vm_size_t page_size;
|
||||
vm_statistics_data_t vm_stat;
|
||||
kern_return_t kern;
|
||||
|
||||
kern = host_page_size(host_port, &page_size);
|
||||
if (kern != KERN_SUCCESS) return 0;
|
||||
kern = host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size);
|
||||
if (kern != KERN_SUCCESS) return 0;
|
||||
return vm_stat.free_count * page_size;
|
||||
}
|
||||
#import "objc/runtime.h"
|
||||
|
||||
@interface SDAnimatedImageView () <CALayerDelegate> {
|
||||
NSRunLoopMode _runLoopMode;
|
||||
BOOL _initFinished; // Extra flag to mark the `commonInit` is called
|
||||
}
|
||||
|
||||
@property (nonatomic, strong, readwrite) UIImage *currentFrame;
|
||||
@property (nonatomic, assign, readwrite) NSUInteger currentFrameIndex;
|
||||
@property (nonatomic, assign, readwrite) NSUInteger currentLoopCount;
|
||||
@property (nonatomic, assign) NSUInteger totalFrameCount;
|
||||
@property (nonatomic, assign) NSUInteger totalLoopCount;
|
||||
@property (nonatomic, strong) UIImage<SDAnimatedImage> *animatedImage;
|
||||
@property (nonatomic, strong) NSMutableDictionary<NSNumber *, UIImage *> *frameBuffer;
|
||||
@property (nonatomic, assign) NSTimeInterval currentTime;
|
||||
@property (nonatomic, assign) BOOL bufferMiss;
|
||||
@property (nonatomic, assign) BOOL shouldAnimate;
|
||||
@property (nonatomic, assign) BOOL isProgressive;
|
||||
@property (nonatomic, assign) NSUInteger maxBufferCount;
|
||||
@property (nonatomic, strong) NSOperationQueue *fetchQueue;
|
||||
@property (nonatomic, strong) dispatch_semaphore_t lock;
|
||||
@property (nonatomic, assign) CGFloat animatedImageScale;
|
||||
@property (nonatomic, strong) SDDisplayLink *displayLink;
|
||||
@property (nonatomic,strong) SDAnimatedImagePlayer *player; // The animation player.
|
||||
@property (nonatomic) CALayer *imageViewLayer; // The actual rendering layer.
|
||||
|
||||
@end
|
||||
|
@ -124,59 +94,11 @@ static NSUInteger SDDeviceFreeMemory() {
|
|||
self.shouldIncrementalLoad = YES;
|
||||
#if SD_MAC
|
||||
self.wantsLayer = YES;
|
||||
#endif
|
||||
#if SD_UIKIT
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
|
||||
#endif
|
||||
// Mark commonInit finished
|
||||
_initFinished = YES;
|
||||
}
|
||||
|
||||
- (void)resetAnimatedImage
|
||||
{
|
||||
self.animatedImage = nil;
|
||||
self.totalFrameCount = 0;
|
||||
self.totalLoopCount = 0;
|
||||
// reset current state
|
||||
[self resetCurrentFrameIndex];
|
||||
self.shouldAnimate = NO;
|
||||
self.isProgressive = NO;
|
||||
self.maxBufferCount = 0;
|
||||
self.animatedImageScale = 1;
|
||||
[_fetchQueue cancelAllOperations];
|
||||
// clear buffer cache
|
||||
[self clearFrameBuffer];
|
||||
}
|
||||
|
||||
- (void)resetProgressiveImage
|
||||
{
|
||||
self.animatedImage = nil;
|
||||
self.totalFrameCount = 0;
|
||||
self.totalLoopCount = 0;
|
||||
// preserve current state
|
||||
self.shouldAnimate = NO;
|
||||
self.isProgressive = YES;
|
||||
self.maxBufferCount = 0;
|
||||
self.animatedImageScale = 1;
|
||||
// preserve buffer cache
|
||||
}
|
||||
|
||||
- (void)resetCurrentFrameIndex
|
||||
{
|
||||
self.currentFrame = nil;
|
||||
self.currentFrameIndex = 0;
|
||||
self.currentLoopCount = 0;
|
||||
self.currentTime = 0;
|
||||
self.bufferMiss = NO;
|
||||
}
|
||||
|
||||
- (void)clearFrameBuffer
|
||||
{
|
||||
SD_LOCK(self.lock);
|
||||
[_frameBuffer removeAllObjects];
|
||||
SD_UNLOCK(self.lock);
|
||||
}
|
||||
|
||||
#pragma mark - Accessors
|
||||
#pragma mark Public
|
||||
|
||||
|
@ -189,46 +111,64 @@ static NSUInteger SDDeviceFreeMemory() {
|
|||
// Check Progressive rendering
|
||||
[self updateIsProgressiveWithImage:image];
|
||||
|
||||
if (self.isProgressive) {
|
||||
// Reset all value, but keep current state
|
||||
[self resetProgressiveImage];
|
||||
} else {
|
||||
if (!self.isProgressive) {
|
||||
// Stop animating
|
||||
[self stopAnimating];
|
||||
// Reset all value
|
||||
[self resetAnimatedImage];
|
||||
self.player = nil;
|
||||
self.currentFrame = nil;
|
||||
self.currentFrameIndex = 0;
|
||||
self.currentLoopCount = 0;
|
||||
}
|
||||
|
||||
// We need call super method to keep function. This will impliedly call `setNeedsDisplay`. But we have no way to avoid this when using animated image. So we call `setNeedsDisplay` again at the end.
|
||||
super.image = image;
|
||||
if ([image.class conformsToProtocol:@protocol(SDAnimatedImage)]) {
|
||||
NSUInteger animatedImageFrameCount = ((UIImage<SDAnimatedImage> *)image).animatedImageFrameCount;
|
||||
// Check the frame count
|
||||
if (animatedImageFrameCount <= 1) {
|
||||
if (!self.player) {
|
||||
id<SDAnimatedImageProvider> provider;
|
||||
// Check progressive loading
|
||||
if (self.isProgressive) {
|
||||
provider = [self progressiveAnimatedCoderForImage:image];
|
||||
} else {
|
||||
provider = (id<SDAnimatedImage>)image;
|
||||
}
|
||||
// Create animted player
|
||||
self.player = [SDAnimatedImagePlayer playerWithProvider:provider];
|
||||
} else {
|
||||
// Update Frame Count
|
||||
self.player.totalFrameCount = [(id<SDAnimatedImage>)image animatedImageFrameCount];
|
||||
}
|
||||
|
||||
if (!self.player) {
|
||||
// animated player nil means the image format is not supported, or frame count <= 1
|
||||
return;
|
||||
}
|
||||
// If progressive rendering is disabled but animated image is incremental. Only show poster image
|
||||
if (!self.isProgressive && image.sd_isIncremental) {
|
||||
return;
|
||||
}
|
||||
self.animatedImage = (UIImage<SDAnimatedImage> *)image;
|
||||
self.totalFrameCount = animatedImageFrameCount;
|
||||
// Get the current frame and loop count.
|
||||
self.totalLoopCount = self.animatedImage.animatedImageLoopCount;
|
||||
// Get the scale
|
||||
self.animatedImageScale = image.scale;
|
||||
if (!self.isProgressive) {
|
||||
self.currentFrame = image;
|
||||
SD_LOCK(self.lock);
|
||||
self.frameBuffer[@(self.currentFrameIndex)] = self.currentFrame;
|
||||
SD_UNLOCK(self.lock);
|
||||
|
||||
// Custom Loop Count
|
||||
if (self.shouldCustomLoopCount) {
|
||||
self.player.totalLoopCount = self.animationRepeatCount;
|
||||
}
|
||||
|
||||
// Setup handler
|
||||
@weakify(self);
|
||||
self.player.animationFrameHandler = ^(NSUInteger index, UIImage * frame) {
|
||||
@strongify(self);
|
||||
self.currentFrameIndex = index;
|
||||
self.currentFrame = frame;
|
||||
[self.imageViewLayer setNeedsDisplay];
|
||||
};
|
||||
self.player.animationLoopHandler = ^(NSUInteger loopCount) {
|
||||
@strongify(self);
|
||||
self.currentLoopCount = loopCount;
|
||||
// Progressive image reach the current last frame index. Keep the state and pause animating. Wait for later restart
|
||||
if (self.isProgressive) {
|
||||
NSUInteger lastFrameIndex = self.player.totalFrameCount;
|
||||
[self.player seekToFrameAtIndex:lastFrameIndex loopCount:0];
|
||||
[self.player pausePlaying];
|
||||
}
|
||||
};
|
||||
|
||||
// Ensure disabled highlighting; it's not supported (see `-setHighlighted:`).
|
||||
super.highlighted = NO;
|
||||
|
||||
// Calculate max buffer size
|
||||
[self calculateMaxBufferCount];
|
||||
// Update should animate
|
||||
[self updateShouldAnimate];
|
||||
if (self.shouldAnimate) {
|
||||
|
@ -239,95 +179,26 @@ static NSUInteger SDDeviceFreeMemory() {
|
|||
}
|
||||
}
|
||||
|
||||
#pragma mark - Configuration
|
||||
|
||||
- (void)setRunLoopMode:(NSRunLoopMode)runLoopMode
|
||||
{
|
||||
if ([_runLoopMode isEqual:runLoopMode]) {
|
||||
return;
|
||||
}
|
||||
if (_displayLink) {
|
||||
if (_runLoopMode) {
|
||||
[_displayLink removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:_runLoopMode];
|
||||
}
|
||||
if (runLoopMode.length > 0) {
|
||||
[_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:runLoopMode];
|
||||
}
|
||||
}
|
||||
_runLoopMode = [runLoopMode copy];
|
||||
self.player.runLoopMode = runLoopMode;
|
||||
}
|
||||
|
||||
- (NSRunLoopMode)runLoopMode
|
||||
{
|
||||
if (!_runLoopMode) {
|
||||
_runLoopMode = [[self class] defaultRunLoopMode];
|
||||
}
|
||||
return _runLoopMode;
|
||||
return self.player.runLoopMode;
|
||||
}
|
||||
|
||||
- (BOOL)shouldIncrementalLoad {
|
||||
- (BOOL)shouldIncrementalLoad
|
||||
{
|
||||
if (!_initFinished) {
|
||||
return YES; // Defaults to YES
|
||||
}
|
||||
return _initFinished;
|
||||
}
|
||||
|
||||
#pragma mark - Private
|
||||
- (NSOperationQueue *)fetchQueue
|
||||
{
|
||||
if (!_fetchQueue) {
|
||||
_fetchQueue = [[NSOperationQueue alloc] init];
|
||||
_fetchQueue.maxConcurrentOperationCount = 1;
|
||||
}
|
||||
return _fetchQueue;
|
||||
}
|
||||
|
||||
- (NSMutableDictionary<NSNumber *,UIImage *> *)frameBuffer
|
||||
{
|
||||
if (!_frameBuffer) {
|
||||
_frameBuffer = [NSMutableDictionary dictionary];
|
||||
}
|
||||
return _frameBuffer;
|
||||
}
|
||||
|
||||
- (dispatch_semaphore_t)lock {
|
||||
if (!_lock) {
|
||||
_lock = dispatch_semaphore_create(1);
|
||||
}
|
||||
return _lock;
|
||||
}
|
||||
|
||||
- (SDDisplayLink *)displayLink {
|
||||
if (!_displayLink) {
|
||||
_displayLink = [SDDisplayLink displayLinkWithTarget:self selector:@selector(displayDidRefresh:)];
|
||||
[_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:self.runLoopMode];
|
||||
}
|
||||
return _displayLink;
|
||||
}
|
||||
|
||||
#pragma mark - Life Cycle
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
#if SD_UIKIT
|
||||
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
|
||||
#endif
|
||||
}
|
||||
|
||||
- (void)didReceiveMemoryWarning:(NSNotification *)notification {
|
||||
[_fetchQueue cancelAllOperations];
|
||||
[_fetchQueue addOperationWithBlock:^{
|
||||
NSNumber *currentFrameIndex = @(self.currentFrameIndex);
|
||||
SD_LOCK(self.lock);
|
||||
NSArray *keys = self.frameBuffer.allKeys;
|
||||
// only keep the next frame for later rendering
|
||||
for (NSNumber * key in keys) {
|
||||
if (![key isEqualToNumber:currentFrameIndex]) {
|
||||
[self.frameBuffer removeObjectForKey:key];
|
||||
}
|
||||
}
|
||||
SD_UNLOCK(self.lock);
|
||||
}];
|
||||
}
|
||||
|
||||
#pragma mark - UIView Method Overrides
|
||||
#pragma mark Observing View-Related Changes
|
||||
|
||||
|
@ -408,8 +279,8 @@ static NSUInteger SDDeviceFreeMemory() {
|
|||
|
||||
- (void)startAnimating
|
||||
{
|
||||
if (self.animatedImage) {
|
||||
[self.displayLink start];
|
||||
if (self.player) {
|
||||
[self.player startPlaying];
|
||||
} else {
|
||||
#if SD_UIKIT
|
||||
[super startAnimating];
|
||||
|
@ -419,15 +290,14 @@ static NSUInteger SDDeviceFreeMemory() {
|
|||
|
||||
- (void)stopAnimating
|
||||
{
|
||||
if (self.animatedImage) {
|
||||
[_fetchQueue cancelAllOperations];
|
||||
// Using `_displayLink` here because when UIImageView dealloc, it may trigger `[self stopAnimating]`, we already release the display link in SDAnimatedImageView's dealloc method.
|
||||
[_displayLink stop];
|
||||
if (self.player) {
|
||||
if (self.resetFrameIndexWhenStopped) {
|
||||
[self resetCurrentFrameIndex];
|
||||
[self.player stopPlaying];
|
||||
} else {
|
||||
[self.player pausePlaying];
|
||||
}
|
||||
if (self.clearBufferWhenStopped) {
|
||||
[self clearFrameBuffer];
|
||||
[self.player clearFrameBuffer];
|
||||
}
|
||||
} else {
|
||||
#if SD_UIKIT
|
||||
|
@ -436,18 +306,16 @@ static NSUInteger SDDeviceFreeMemory() {
|
|||
}
|
||||
}
|
||||
|
||||
#if SD_UIKIT
|
||||
- (BOOL)isAnimating
|
||||
{
|
||||
BOOL isAnimating = NO;
|
||||
if (self.animatedImage) {
|
||||
isAnimating = self.displayLink.isRunning;
|
||||
if (self.player) {
|
||||
return self.player.isPlaying;
|
||||
} else {
|
||||
#if SD_UIKIT
|
||||
isAnimating = [super isAnimating];
|
||||
#endif
|
||||
return [super isAnimating];
|
||||
}
|
||||
return isAnimating;
|
||||
}
|
||||
#endif
|
||||
|
||||
#if SD_MAC
|
||||
- (void)setAnimates:(BOOL)animates
|
||||
|
@ -466,7 +334,7 @@ static NSUInteger SDDeviceFreeMemory() {
|
|||
- (void)setHighlighted:(BOOL)highlighted
|
||||
{
|
||||
// Highlighted image is unsupported for animated images, but implementing it breaks the image view when embedded in a UICollectionViewCell.
|
||||
if (!self.animatedImage) {
|
||||
if (!self.player) {
|
||||
[super setHighlighted:highlighted];
|
||||
}
|
||||
}
|
||||
|
@ -484,7 +352,7 @@ static NSUInteger SDDeviceFreeMemory() {
|
|||
#else
|
||||
BOOL isVisible = self.window && self.superview && ![self isHidden] && self.alpha > 0.0;
|
||||
#endif
|
||||
self.shouldAnimate = self.animatedImage && self.totalFrameCount > 1 && isVisible;
|
||||
self.shouldAnimate = self.player && isVisible;
|
||||
}
|
||||
|
||||
// Update progressive status only after `setImage:` call.
|
||||
|
@ -497,157 +365,32 @@ static NSUInteger SDDeviceFreeMemory() {
|
|||
}
|
||||
// We must use `image.class conformsToProtocol:` instead of `image conformsToProtocol:` here
|
||||
// Because UIKit on macOS, using internal hard-coded override method, which returns NO
|
||||
if ([image.class conformsToProtocol:@protocol(SDAnimatedImage)] && image.sd_isIncremental) {
|
||||
id<SDAnimatedImageCoder> currentAnimatedCoder = [self progressiveAnimatedCoderForImage:image];
|
||||
if (currentAnimatedCoder) {
|
||||
UIImage *previousImage = self.image;
|
||||
if ([previousImage.class conformsToProtocol:@protocol(SDAnimatedImage)] && previousImage.sd_isIncremental) {
|
||||
NSData *previousData = [((UIImage<SDAnimatedImage> *)previousImage) animatedImageData];
|
||||
NSData *currentData = [((UIImage<SDAnimatedImage> *)image) animatedImageData];
|
||||
// Check whether to use progressive rendering or not
|
||||
if (!previousData || !currentData) {
|
||||
// Early return
|
||||
return;
|
||||
}
|
||||
|
||||
// Warning: normally the `previousData` is same instance as `currentData` because our `SDAnimatedImage` class share the same `coder` instance internally. But there may be a race condition, that later retrived `currentData` is already been updated and it's not the same instance as `previousData`.
|
||||
// And for protocol extensible design, we should not assume `SDAnimatedImage` protocol implementations always share same instance. So both of two reasons, we need that `rangeOfData` check.
|
||||
if ([currentData isEqualToData:previousData]) {
|
||||
// If current data is the same data (or instance) as previous data
|
||||
self.isProgressive = YES;
|
||||
} else if (currentData.length > previousData.length) {
|
||||
// If current data is appended by previous data, use `NSDataSearchAnchored`, search is limited to start of currentData
|
||||
NSRange range = [currentData rangeOfData:previousData options:NSDataSearchAnchored range:NSMakeRange(0, previousData.length)];
|
||||
if (range.location != NSNotFound) {
|
||||
// Contains hole previous data and they start with the same beginning
|
||||
self.isProgressive = YES;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Previous image is not progressive, so start progressive rendering
|
||||
if (!previousImage) {
|
||||
// If current animated coder supports progressive, and no previous image to check, start progressive loading
|
||||
self.isProgressive = YES;
|
||||
} else {
|
||||
id<SDAnimatedImageCoder> previousAnimatedCoder = [self progressiveAnimatedCoderForImage:previousImage];
|
||||
if (previousAnimatedCoder == currentAnimatedCoder) {
|
||||
// If current animated coder is the same as previous, start progressive loading
|
||||
self.isProgressive = YES;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)displayDidRefresh:(SDDisplayLink *)displayLink
|
||||
// Check if image can represent a `Progressive Animated Image` during loading
|
||||
- (id<SDAnimatedImageCoder, SDProgressiveImageCoder>)progressiveAnimatedCoderForImage:(UIImage *)image
|
||||
{
|
||||
// If for some reason a wild call makes it through when we shouldn't be animating, bail.
|
||||
// Early return!
|
||||
if (!self.shouldAnimate) {
|
||||
return;
|
||||
}
|
||||
// Calculate refresh duration
|
||||
NSTimeInterval duration = self.displayLink.duration;
|
||||
|
||||
NSUInteger totalFrameCount = self.totalFrameCount;
|
||||
NSUInteger currentFrameIndex = self.currentFrameIndex;
|
||||
NSUInteger nextFrameIndex = (currentFrameIndex + 1) % totalFrameCount;
|
||||
|
||||
// Check if we have the frame buffer firstly to improve performance
|
||||
if (!self.bufferMiss) {
|
||||
// Then check if timestamp is reached
|
||||
self.currentTime += duration;
|
||||
NSTimeInterval currentDuration = [self.animatedImage animatedImageDurationAtIndex:currentFrameIndex];
|
||||
if (self.currentTime < currentDuration) {
|
||||
// Current frame timestamp not reached, return
|
||||
return;
|
||||
}
|
||||
self.currentTime -= currentDuration;
|
||||
NSTimeInterval nextDuration = [self.animatedImage animatedImageDurationAtIndex:nextFrameIndex];
|
||||
if (self.currentTime > nextDuration) {
|
||||
// Do not skip frame
|
||||
self.currentTime = nextDuration;
|
||||
if ([image.class conformsToProtocol:@protocol(SDAnimatedImage)] && image.sd_isIncremental && [image respondsToSelector:@selector(animatedCoder)]) {
|
||||
id<SDAnimatedImageCoder> animatedCoder = [(id<SDAnimatedImage>)image animatedCoder];
|
||||
if ([animatedCoder conformsToProtocol:@protocol(SDProgressiveImageCoder)]) {
|
||||
return (id<SDAnimatedImageCoder, SDProgressiveImageCoder>)animatedCoder;
|
||||
}
|
||||
}
|
||||
|
||||
// Update the current frame
|
||||
UIImage *currentFrame;
|
||||
UIImage *fetchFrame;
|
||||
SD_LOCK(self.lock);
|
||||
currentFrame = self.frameBuffer[@(currentFrameIndex)];
|
||||
fetchFrame = currentFrame ? self.frameBuffer[@(nextFrameIndex)] : nil;
|
||||
SD_UNLOCK(self.lock);
|
||||
BOOL bufferFull = NO;
|
||||
if (currentFrame) {
|
||||
SD_LOCK(self.lock);
|
||||
// Remove the frame buffer if need
|
||||
if (self.frameBuffer.count > self.maxBufferCount) {
|
||||
self.frameBuffer[@(currentFrameIndex)] = nil;
|
||||
}
|
||||
// Check whether we can stop fetch
|
||||
if (self.frameBuffer.count == totalFrameCount) {
|
||||
bufferFull = YES;
|
||||
}
|
||||
SD_UNLOCK(self.lock);
|
||||
self.currentFrame = currentFrame;
|
||||
self.currentFrameIndex = nextFrameIndex;
|
||||
self.bufferMiss = NO;
|
||||
[self.imageViewLayer setNeedsDisplay];
|
||||
} else {
|
||||
self.bufferMiss = YES;
|
||||
}
|
||||
|
||||
// Update the loop count when last frame rendered
|
||||
if (nextFrameIndex == 0 && !self.bufferMiss) {
|
||||
// Progressive image reach the current last frame index. Keep the state and stop animating. Wait for later restart
|
||||
if (self.isProgressive) {
|
||||
// Recovery the current frame index and removed frame buffer (See above)
|
||||
self.currentFrameIndex = currentFrameIndex;
|
||||
SD_LOCK(self.lock);
|
||||
self.frameBuffer[@(currentFrameIndex)] = self.currentFrame;
|
||||
SD_UNLOCK(self.lock);
|
||||
[self stopAnimating];
|
||||
return;
|
||||
}
|
||||
// Update the loop count
|
||||
self.currentLoopCount++;
|
||||
// if reached the max loop count, stop animating, 0 means loop indefinitely
|
||||
NSUInteger maxLoopCount = self.shouldCustomLoopCount ? self.animationRepeatCount : self.totalLoopCount;
|
||||
if (maxLoopCount != 0 && (self.currentLoopCount >= maxLoopCount)) {
|
||||
[self stopAnimating];
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Check if we should prefetch next frame or current frame
|
||||
NSUInteger fetchFrameIndex;
|
||||
if (self.bufferMiss) {
|
||||
// When buffer miss, means the decode speed is slower than render speed, we fetch current miss frame
|
||||
fetchFrameIndex = currentFrameIndex;
|
||||
} else {
|
||||
// Or, most cases, the decode speed is faster than render speed, we fetch next frame
|
||||
fetchFrameIndex = nextFrameIndex;
|
||||
}
|
||||
|
||||
if (!fetchFrame && !bufferFull && self.fetchQueue.operationCount == 0) {
|
||||
// Prefetch next frame in background queue
|
||||
UIImage<SDAnimatedImage> *animatedImage = self.animatedImage;
|
||||
@weakify(self);
|
||||
NSOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
|
||||
@strongify(self);
|
||||
if (!self) {
|
||||
return;
|
||||
}
|
||||
UIImage *frame = [animatedImage animatedImageFrameAtIndex:fetchFrameIndex];
|
||||
|
||||
BOOL isAnimating = self.displayLink.isRunning;
|
||||
if (isAnimating) {
|
||||
SD_LOCK(self.lock);
|
||||
self.frameBuffer[@(fetchFrameIndex)] = frame;
|
||||
SD_UNLOCK(self.lock);
|
||||
}
|
||||
// Ensure when self dealloc, it dealloced on the main queue (UIKit/AppKit rule)
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self class];
|
||||
});
|
||||
}];
|
||||
[self.fetchQueue addOperation:operation];
|
||||
}
|
||||
}
|
||||
|
||||
+ (NSString *)defaultRunLoopMode
|
||||
{
|
||||
// Key off `activeProcessorCount` (as opposed to `processorCount`) since the system could shut down cores in certain situations.
|
||||
return [NSProcessInfo processInfo].activeProcessorCount > 1 ? NSRunLoopCommonModes : NSDefaultRunLoopMode;
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
|
@ -656,9 +399,10 @@ static NSUInteger SDDeviceFreeMemory() {
|
|||
|
||||
- (void)displayLayer:(CALayer *)layer
|
||||
{
|
||||
if (self.currentFrame) {
|
||||
layer.contentsScale = self.animatedImageScale;
|
||||
layer.contents = (__bridge id)self.currentFrame.CGImage;
|
||||
UIImage *currentFrame = self.currentFrame;
|
||||
if (currentFrame) {
|
||||
layer.contentsScale = currentFrame.scale;
|
||||
layer.contents = (__bridge id)currentFrame.CGImage;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -696,31 +440,6 @@ static NSUInteger SDDeviceFreeMemory() {
|
|||
|
||||
#endif
|
||||
|
||||
|
||||
#pragma mark - Util
|
||||
- (void)calculateMaxBufferCount {
|
||||
NSUInteger bytes = CGImageGetBytesPerRow(self.currentFrame.CGImage) * CGImageGetHeight(self.currentFrame.CGImage);
|
||||
if (bytes == 0) bytes = 1024;
|
||||
|
||||
NSUInteger max = 0;
|
||||
if (self.maxBufferSize > 0) {
|
||||
max = self.maxBufferSize;
|
||||
} else {
|
||||
// Calculate based on current memory, these factors are by experience
|
||||
NSUInteger total = SDDeviceTotalMemory();
|
||||
NSUInteger free = SDDeviceFreeMemory();
|
||||
max = MIN(total * 0.2, free * 0.6);
|
||||
}
|
||||
|
||||
NSUInteger maxBufferCount = (double)max / (double)bytes;
|
||||
if (!maxBufferCount) {
|
||||
// At least 1 frame
|
||||
maxBufferCount = 1;
|
||||
}
|
||||
|
||||
self.maxBufferCount = maxBufferCount;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
|
|
|
@ -0,0 +1,17 @@
|
|||
/*
|
||||
* This file is part of the SDWebImage package.
|
||||
* (c) Olivier Poitrey <rs@dailymotion.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SDWebImageCompat.h"
|
||||
|
||||
@interface SDDeviceHelper : NSObject
|
||||
|
||||
+ (NSUInteger)totalMemory;
|
||||
+ (NSUInteger)freeMemory;
|
||||
|
||||
@end
|
|
@ -0,0 +1,32 @@
|
|||
/*
|
||||
* This file is part of the SDWebImage package.
|
||||
* (c) Olivier Poitrey <rs@dailymotion.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
#import "SDDeviceHelper.h"
|
||||
#import <mach/mach.h>
|
||||
|
||||
@implementation SDDeviceHelper
|
||||
|
||||
+ (NSUInteger)totalMemory {
|
||||
return (NSUInteger)[[NSProcessInfo processInfo] physicalMemory];
|
||||
}
|
||||
|
||||
+ (NSUInteger)freeMemory {
|
||||
mach_port_t host_port = mach_host_self();
|
||||
mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
|
||||
vm_size_t page_size;
|
||||
vm_statistics_data_t vm_stat;
|
||||
kern_return_t kern;
|
||||
|
||||
kern = host_page_size(host_port, &page_size);
|
||||
if (kern != KERN_SUCCESS) return 0;
|
||||
kern = host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size);
|
||||
if (kern != KERN_SUCCESS) return 0;
|
||||
return vm_stat.free_count * page_size;
|
||||
}
|
||||
|
||||
@end
|
|
@ -16,6 +16,12 @@ static const NSUInteger kTestGIFFrameCount = 5; // local TestImage.gif loop coun
|
|||
@interface SDAnimatedImageView ()
|
||||
|
||||
@property (nonatomic, assign) BOOL isProgressive;
|
||||
@property (nonatomic, strong) SDAnimatedImagePlayer *player;
|
||||
|
||||
@end
|
||||
|
||||
@interface SDAnimatedImagePlayer ()
|
||||
|
||||
@property (nonatomic, strong) NSMutableDictionary<NSNumber *, UIImage *> *frameBuffer;
|
||||
|
||||
@end
|
||||
|
@ -102,6 +108,11 @@ static const NSUInteger kTestGIFFrameCount = 5; // local TestImage.gif loop coun
|
|||
SDAnimatedImage *image = [SDAnimatedImage imageWithData:[self testGIFData]];
|
||||
imageView.image = image;
|
||||
expect(imageView.image).notTo.beNil();
|
||||
#if SD_MAC
|
||||
imageView.animates = YES;
|
||||
#else
|
||||
[imageView startAnimating];
|
||||
#endif
|
||||
expect(imageView.currentFrame).notTo.beNil(); // current frame
|
||||
}
|
||||
|
||||
|
@ -110,6 +121,11 @@ static const NSUInteger kTestGIFFrameCount = 5; // local TestImage.gif loop coun
|
|||
SDAnimatedImage *image = [SDAnimatedImage imageWithData:[self testAPNGPData]];
|
||||
imageView.image = image;
|
||||
expect(imageView.image).notTo.beNil();
|
||||
#if SD_MAC
|
||||
imageView.animates = YES;
|
||||
#else
|
||||
[imageView startAnimating];
|
||||
#endif
|
||||
expect(imageView.currentFrame).notTo.beNil(); // current frame
|
||||
}
|
||||
|
||||
|
@ -312,7 +328,7 @@ static const NSUInteger kTestGIFFrameCount = 5; // local TestImage.gif loop coun
|
|||
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
// 0.5s is not finished, frame index should not be 0
|
||||
expect(imageView.frameBuffer.count).beGreaterThan(0);
|
||||
expect(imageView.player.frameBuffer.count).beGreaterThan(0);
|
||||
expect(imageView.currentFrameIndex).beGreaterThan(0);
|
||||
});
|
||||
|
||||
|
@ -322,7 +338,7 @@ static const NSUInteger kTestGIFFrameCount = 5; // local TestImage.gif loop coun
|
|||
#else
|
||||
imageView.animates = NO;
|
||||
#endif
|
||||
expect(imageView.frameBuffer.count).beGreaterThan(0);
|
||||
expect(imageView.player.frameBuffer.count).beGreaterThan(0);
|
||||
expect(imageView.currentFrameIndex).beGreaterThan(0);
|
||||
|
||||
[imageView removeFromSuperview];
|
||||
|
@ -350,7 +366,7 @@ static const NSUInteger kTestGIFFrameCount = 5; // local TestImage.gif loop coun
|
|||
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
// 0.5s is not finished, frame index should not be 0
|
||||
expect(imageView.frameBuffer.count).beGreaterThan(0);
|
||||
expect(imageView.player.frameBuffer.count).beGreaterThan(0);
|
||||
expect(imageView.currentFrameIndex).beGreaterThan(0);
|
||||
});
|
||||
|
||||
|
@ -360,7 +376,7 @@ static const NSUInteger kTestGIFFrameCount = 5; // local TestImage.gif loop coun
|
|||
#else
|
||||
imageView.animates = NO;
|
||||
#endif
|
||||
expect(imageView.frameBuffer.count).equal(0);
|
||||
expect(imageView.player.frameBuffer.count).equal(0);
|
||||
expect(imageView.currentFrameIndex).equal(0);
|
||||
|
||||
[imageView removeFromSuperview];
|
||||
|
|
|
@ -50,6 +50,7 @@
|
|||
expect(duration).equal(1.0 / 60);
|
||||
[displayLink addToRunLoop:NSRunLoop.mainRunLoop forMode:NSRunLoopCommonModes];
|
||||
[displayLink start];
|
||||
expect(displayLink.isRunning).beTruthy();
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
expect(displayLink.isRunning).beTruthy();
|
||||
[displayLink stop];
|
||||
|
|
|
@ -55,6 +55,7 @@ FOUNDATION_EXPORT const unsigned char WebImageVersionString[];
|
|||
#import <SDWebImage/SDAnimatedImage.h>
|
||||
#import <SDWebImage/SDAnimatedImageView.h>
|
||||
#import <SDWebImage/SDAnimatedImageView+WebCache.h>
|
||||
#import <SDWebImage/SDAnimatedImagePlayer.h>
|
||||
#import <SDWebImage/SDImageCodersManager.h>
|
||||
#import <SDWebImage/SDImageCoder.h>
|
||||
#import <SDWebImage/SDImageAPNGCoder.h>
|
||||
|
|
Loading…
Reference in New Issue