CAKeyframeAnimation 关键帧动画
1.添加position动画
CAKeyframeAnimation * _animation=[CAKeyframeAnimation animation];
_animation.keyPath=@"position";
NSMutableArray * _frames=[NSMutableArray new];
for(int i=0;i<10*_totalFilterTime;i++){
float _leftBorder=_leftButton.frame.origin.x+i/(_totalFilterTime*10.0)*(_upperView.frame.size.width-kFlagViewWidth);
NSValue * _frameValue=[NSValue valueWithCGPoint:CGPointMake(_leftBorder+_size.width/2, _flagView.frame.origin.y+_flagView.frame.size.height/2)];
[_frames addObject:_frameValue];
}
_animation.values=_frames;
_animation.duration=_totalFilterTime;
_animation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
[_flagView.layer addAnimation:_animation forKey:nil];
2.使用CAKeyframeAnimation显示GIF
【1】.首先解析出GIF分帧数据
-(float)getFrameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source
{
float _frameDuration = 0.1f;
CFDictionaryRef _properties = CGImageSourceCopyPropertiesAtIndex(source, index, nil);
NSDictionary * _dict = (__bridge NSDictionary *)_properties;
NSDictionary * _gifDict = [_dict objectForKey:(NSString *)kCGImagePropertyGIFDictionary];
NSNumber * _delayUnclamped = _gifDict[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];// 获取该帧图片播放时长
if (_delayUnclamped) {
_frameDuration = [_delayUnclamped floatValue];
}
else {
NSNumber * _delayTime = [_gifDict objectForKey:(NSString *)kCGImagePropertyGIFDelayTime];
if (_delayTime) {
_frameDuration = [_delayTime floatValue];
}
}
if (_frameDuration < 0.011f) {
_frameDuration = 0.100f;
}
CFRelease(_properties);
return _frameDuration;
}
【2】.根据每帧的图片和时长设置CAKeyframeAnimation
CAKeyframeAnimation * _animation=[CAKeyframeAnimation animationWithKeyPath:@"contents"];
NSMutableArray * _timeArray=[NSMutableArray new];
NSMutableArray * _imageArray=[NSMutableArray new];
float _currentTime=0;
for(NSInteger i=_index;i<MIN(_index+_lenght, _allZhens.count);i++){
NSDictionary * _dict=[_allZhens objectForKey:[NSNumber numberWithInteger:i]];
UIImage * _image=[_dict objectForKey:kPerZhenImage];
[_imageArray addObject:(__bridge UIImage *)_image.CGImage];
[_timeArray addObject:[NSNumber numberWithFloat:_currentTime/_totalFilterTime]];
_currentTime+=[[_dict objectForKey:kPerZhenDuration] floatValue];
}
_animation.keyTimes=_timeArray;
_animation.values=_imageArray;
_animation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
_animation.duration=_totalFilterTime;
[_gifImageView.layer addAnimation:_animation forKey:@"gifAnimation"];