網上找過幾個跑馬燈實現,都存在 CPU 佔用飆高的問題,多數是用 NSTimer 或 CADisplayLink 不斷改 frame 導致的。改用 CABasicAnimation 之後,動畫交給渲染服務器執行,CPU 基本處於空閒狀態,代碼也更短。
#import <UIKit/UIKit.h> @interface LoopView : UIView @property(nonatomic,strong)NSString *Iformation; @property(nonatomic,strong)NSString *Image; @end
#import "LoopView.h" #import "UIImageView+WebCache.h" @interface LoopView(){ UILabel *AD; UIImageView *headImage; CABasicAnimation *animation; CABasicAnimation *animationhead; } @end @implementation LoopView -(instancetype)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (self) { AD = [[UILabel alloc]initWithFrame:CGRectMake(28*WPSCREEN_WIDTH_RATIO, 0, self.frame.size.width, self.frame.size.height)]; [self addSubview:AD]; AD.textColor = TJXColor(146, 152, 169); AD.font = [UIFont fontWithName:@"Gotham-Book" size:12*WPSCREEN_WIDTH_RATIO]; AD.textAlignment = NSTextAlignmentLeft; headImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20*WPSCREEN_WIDTH_RATIO, 20*WPSCREEN_WIDTH_RATIO)]; [self addSubview:headImage]; headImage.layer.cornerRadius = 10; headImage.layer.masksToBounds = YES; [self sssss]; [self headimage]; } return self; } -(void)setIformation:(NSString *)Iformation{ AD.text =Iformation; } -(void)setImage:(NSString *)Image{ [headImage sd_setImageWithURL:[NSURL URLWithString:Image]]; } -(void)sssss{ animation = [CABasicAnimation animationWithKeyPath:@"position"]; // 動畫選項的設定 animation.duration = 2; // 持續時間 animation.repeatCount = MAXFLOAT; // 重復次數 animation.removedOnCompletion = NO; animation.autoreverses = NO; // 起始幀和終了幀的設定 animation.fromValue = [NSValue valueWithCGPoint:CGPointMake(AD.layer.position.x, 30*WPSCREEN_HIGTH_RATIO)]; // 起始幀 animation.toValue = [NSValue valueWithCGPoint:CGPointMake(AD.layer.position.x, AD.layer.position.y-20*WPSCREEN_HIGTH_RATIO)]; // 終了幀 // 添加動畫 [AD.layer addAnimation:animation forKey:@"AnimationMoveY"]; // [headImage.layer addAnimation:animation forKey:@"AnimationMoveY"]; } -(void)headimage{ animationhead = [CABasicAnimation animationWithKeyPath:@"position"]; // 動畫選項的設定 animationhead.duration = 2; // 持續時間 animationhead.repeatCount = MAXFLOAT; // 重復次數 animationhead.removedOnCompletion = NO; animationhead.autoreverses = NO; // 起始幀和終了幀的設定 animationhead.fromValue = [NSValue valueWithCGPoint:CGPointMake(headImage.layer.position.x, 30*WPSCREEN_HIGTH_RATIO)]; // 起始幀 animationhead.toValue = [NSValue valueWithCGPoint:CGPointMake(headImage.layer.position.x, headImage.layer.position.y-20*WPSCREEN_HIGTH_RATIO)]; // 終了幀 // 添加動畫 [headImage.layer addAnimation:animationhead forKey:@"AnimationMoveY"]; }
關鍵在於用 position 作為動畫 keyPath,把起止位置寫成 fromValue 與 toValue,再令 repeatCount = MAXFLOAT 無限循環。文字與頭像各自一條動畫,參數保持一致就能同步運動。由於 Core Animation 在渲染進程中執行,滑動列表時也不會掉幀。
以上就是基於 CABasicAnimation 實現跑馬燈的完整代碼,可直接按需定制速度、位移與樣式。