自定义view的.m文件中写
#import "KKView.h" @interface KKView() /** 图片的y值 */ @property (nonatomic, assign) CGFloat imgY; @end @implementation KKView - (void)awakeFromNib{ // 创建CADisplayLink, 默认每秒60次 CADisplayLink *display = [CADisplayLink displayLinkWithTarget:self selector:@selector(updataImage)]; // 将CADisplayLink加入到消息循环中 [display addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; } - (void)updataImage{ // 这里会掉用drawRect方法 [self setNeedsDisplay]; } - (void)drawRect:(CGRect)rect { CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextClearRect(ctx, rect); CGImageRef img = [UIImage imageNamed:@"snow"].CGImage; CGRect imgRect; if (_imgY>rect.size.height) { _imgY = 0; } _imgY+=1; imgRect.origin.y = _imgY; imgRect.origin.x = 0; imgRect.size = CGSizeMake(50, 50); CGContextDrawImage(ctx, imgRect, img); } @end
时间: 2024-10-13 09:51:20