1民效、選擇CADisplayLink而不使用NSTimer?
- 如果以后每隔一段時間需要重繪,一般不使用NSTimer,因為NSTimer刷新會有延時遂蛀,使用CADisplayLink不會刷新的時候有延遲
2匙铡、代碼實現(xiàn):
- 自定義視圖DrawView
// .h 文件
#import <UIKit/UIKit.h>
@interface DrawView : UIView
@end
// .m文件實現(xiàn)
#import "DrawView.h"
@implementation DrawView
- (void)drawRect:(CGRect)rect {
// Drawing code
static CGFloat snowY = 0;
UIImage *image = [UIImage imageNamed:@"雪花"];
[image drawAtPoint:CGPointMake(0, snowY)];
snowY += 10;
if (snowY > rect.size.height) {
snowY = 0;
}
}
//setNeedsDisplay 綁定一個標識,等待下次刷新的時候才會調用drawRect方法
- (nonnull instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
self.backgroundColor = [UIColor blackColor];
// 定時器
// 每次屏幕刷新的時候就會調用,屏幕一秒刷新60次
CADisplayLink *link = [CADisplayLink displayLinkWithTarget:selfselector:@selector(setNeedsDisplay)];
// 只要把定時器添加到主運行循環(huán)就能自動執(zhí)行
[link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
// setNeedsDisplay:底層并不會馬上調用drawRect,只會給當前的控件綁定一個刷新的標識,每次屏幕刷新的時候,就會把綁定了刷新(重繪)標識的控件重新刷新(繪制)一次,就會調用drawRect去重繪
// 如果以后每隔一段時間需要重繪,一般不使用NSTimer,使用CADisplayLink,不會刷新的時候有延遲 }
}
return self;
}
@end
- 2.使用DrawView
#import "ViewController.h"
#import "DrawView.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
DrawView *drawV = [[DrawView alloc] init];
drawV.frame = self.view.frame;
[self.view addSubview:drawV];
}
@end