iOS GIF 播放暂停功能实现 - Objective-C 代码示例
是的,iOS 上可以通过控制 UIImageView 的动画播放来暂停和继续播放 GIF。
Objective-C 代码如下:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (nonatomic, strong) UIImageView *gifImageView;
@property (nonatomic, assign) BOOL isPlaying;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 初始化 UIImageView
self.gifImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
self.gifImageView.center = self.view.center;
[self.view addSubview:self.gifImageView];
// 加载 GIF 图片
NSString *gifPath = [[NSBundle mainBundle] pathForResource: 'your_gif_image' ofType: 'gif'];
NSData *gifData = [NSData dataWithContentsOfFile:gifPath];
self.gifImageView.image = [UIImage sd_imageWithData:gifData];
// 添加手势
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
[self.view addGestureRecognizer:tapGesture];
}
- (void)handleTapGesture:(UITapGestureRecognizer *)sender {
if (self.isPlaying) {
// 暂停动画播放
[self.gifImageView stopAnimating];
} else {
// 继续动画播放
[self.gifImageView startAnimating];
}
self.isPlaying = !self.isPlaying;
}
@end
上述代码中,首先在 viewDidLoad 方法中初始化 UIImageView 并加载 GIF 图片。然后,添加一个手势,当用户点击屏幕时,根据 isPlaying 属性来判断当前是否正在播放动画,如果是,则调用 stopAnimating 方法暂停播放,否则调用 startAnimating 方法继续播放。最后,更新 isPlaying 属性的值。
原文地址: https://www.cveoy.top/t/topic/o9Oe 著作权归作者所有。请勿转载和采集!