GCD定时器精确度高,不必受Nsrunloop各种mode的影响
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
/// 用DISPATCH_now系统休眠时,不进行计时 dispatch_walltime(NULL, 0)
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1*NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(self.timer, ^{
/// 内部处理各种任务
NSLog(@"计时");
});
dispatch_resume(self.timer);
/// 取消定时器
dispatch_source_cancel(_timer);
- (void)initTimer{
/// 获取全局队列
///dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 初始化心形动画
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
/// 用DISPATCH_now系统休眠时,不进行计时 dispatch_walltime(NULL, 0)
dispatch_source_set_timer(self.timer, DISPATCH_TIME_NOW, 1*NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(self.timer, ^{
NSLog(@"计时");
[self showMoreLoveAnimateFromView:self.shareBtn addToView:self.view];
});
dispatch_resume(self.timer);
}
- (void)showMoreLoveAnimateFromView:(UIView *)fromView addToView:(UIView *)addToView {
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 25)];
CGRect loveFrame = [fromView convertRect:fromView.frame toView:addToView];
CGPoint position = CGPointMake(fromView.layer.position.x, loveFrame.origin.y - 30);
imageView.layer.position = position;
NSArray *imgArr = @[@"heart_1",@"heart_2",@"heart_3",@"heart_4",@"heart_5",@"heart_1"];
NSInteger img = arc4random()%6;
imageView.image = [UIImage imageNamed:imgArr[img]];
[addToView addSubview:imageView];
imageView.transform = CGAffineTransformMakeScale(0.01, 0.01);
[UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveEaseOut animations:^{
imageView.transform = CGAffineTransformIdentity;
} completion:nil];
CGFloat duration = 3 + arc4random()%5;
CAKeyframeAnimation *positionAnimate = [CAKeyframeAnimation animationWithKeyPath:@"position"];
positionAnimate.repeatCount = 1;
positionAnimate.duration = duration;
positionAnimate.fillMode = kCAFillModeForwards;
positionAnimate.removedOnCompletion = NO;
UIBezierPath *sPath = [UIBezierPath bezierPath];
[sPath moveToPoint:position];
CGFloat sign = arc4random()%2 == 1 ? 1 : -1;
CGFloat controlPointValue = (arc4random()%50 + arc4random()%100) * sign;
[sPath addCurveToPoint:CGPointMake(position.x, position.y - 300) controlPoint1:CGPointMake(position.x - controlPointValue, position.y - 150) controlPoint2:CGPointMake(position.x + controlPointValue, position.y - 150)];
positionAnimate.path = sPath.CGPath;
[imageView.layer addAnimation:positionAnimate forKey:@"heartAnimated"];
[UIView animateWithDuration:duration animations:^{
imageView.layer.opacity = 0;
} completion:^(BOOL finished) {
[imageView removeFromSuperview];
}];
}
效果图
底下的心形动画 是用定时器做出来的