本次记录是在子线程中进行计算给出随机值,并在主线程中隔时创建label进行动画上浮展示效果。
![](https://img.haomeiwen.com/i5109952/bc97ff6944b69581.gif)
//时间、上浮速度、创建多少都可控。
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
// 可以用该语句查看当前线程
NSLog(@"当前线程--%@", [NSThread currentThread]);
// 此处需要写一个异步任务,是因为需要开辟一个新的线程去反复执行你的代码块,否则会阻塞主线程
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
while (TRUE) {
// 每隔5秒执行一次(当前线程阻塞5秒)
[NSThread sleepForTimeInterval:0.2];
// [[UIApplication sharedApplication] cancelAllLocalNotifications];
// 这里写你要反复处理的代码,如网络请求
// NSLog(@"***每5秒输出一次这段文字***");
int a = arc4random()%5;
UIGraphicsBeginImageContext(CGSizeMake(a, a));//设置上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextBeginPath(ctx);
CGContextAddArc(ctx, a/2, a/2, a/2, 0, 2*M_PI, 0);
CGContextSetRGBFillColor (ctx, 2, 2, 0, 1.0);//设置填充颜色
CGContextFillPath(ctx);
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
dispatch_async(dispatch_get_main_queue(), ^{
UILabel*theLabOne = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-arc4random()%60, self.view.frame.size.height-arc4random()%60-20, a, a)];
theLabOne.backgroundColor = [UIColor greenColor];
[self.view addSubview:theLabOne];
[UIView animateKeyframesWithDuration:(10.0)//动画持续时间
delay:(0.01)//动画延迟执行的时间
options:(UIViewAnimationOptionTransitionNone)//动画的过渡效果
animations:^{
//执行的关键帧动画
//执行的动画
theLabOne.frame = CGRectMake(self.view.frame.size.width/2-arc4random()%60, -10, a, a);
}
completion:^(BOOL finished) {
}];
});
// [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
};
});
网友评论