Skip to content

Instantly share code, notes, and snippets.

@phildow
Created August 26, 2015 20:17
Show Gist options
  • Save phildow/eb2bd5139b1470eff343 to your computer and use it in GitHub Desktop.
Save phildow/eb2bd5139b1470eff343 to your computer and use it in GitHub Desktop.
#import <UIKit/UIKit.h>
@interface UIImage (SDWebImageAnimatedGifSwizzle)
@end
//
// UIImage+SDWebImageAnimatedGifSwizzle.m
//
// Created by Philip Dow on 8/26/15.
// Just Use It License
//
#import "UIImage+SDWebImageAnimatedGifSwizzle.h"
#import <SDWebImage/UIImage+MultiFormat.h>
#import <SDWebImage/UIImage+GIF.h>
#import <objc/runtime.h>
// In case you need a refresher: http://nshipster.com/method-swizzling/
// Swizzling + (UIImage *)sd_animatedGIFWithData:(NSData *)data;
// to return an unanimated image
@interface UIImage (SDWebImageAnimatedGifSwizzleExtern)
+ (UIImageOrientation)sd_imageOrientationFromImageData:(NSData *)imageData;
@end
#pragma mark -
@implementation UIImage (SDWebImageAnimatedGifSwizzle)
+ (void)load
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// Class class = [self class];
Class class = object_getClass((id)self);
SEL originalSelector = @selector(sd_animatedGIFWithData:);
SEL swizzledSelector = @selector(sd_swizzle_animatedGIFWithData:);
// Method originalMethod = class_getInstanceMethod(class, originalSelector);
// Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
Method originalMethod = class_getClassMethod(class, originalSelector);
Method swizzledMethod = class_getClassMethod(class, swizzledSelector);
// When swizzling a class method, use the following:
// Class class = object_getClass((id)self);
// ...
// Method originalMethod = class_getClassMethod(class, originalSelector);
// Method swizzledMethod = class_getClassMethod(class, swizzledSelector);
BOOL didAddMethod =
class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
+ (UIImage*) sd_swizzle_animatedGIFWithData:(NSData*)data
{
UIImage *image = [[UIImage alloc] initWithData:data];
UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data];
if (orientation != UIImageOrientationUp) {
image = [UIImage imageWithCGImage:image.CGImage scale:image.scale orientation:orientation];
}
return image;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment