在網頁開發當中跑馬燈是常用到的,用來顯示通知等,在游戲開發當中也如此。
首先來看看效果圖:
接下來就簡單看看這效果是怎么實現的。
實現方法
1、首先我們從這個圖片里面能聯想到如果實現這個效果必然需要使用到動畫,或者還有有用scrollView的思路,這里我是用的動畫的方式實現的。
2、.h文件
自定義一個繼承UIView的LGJAutoRunLabel類,在.h文件中:
@class LGJAutoRunLabel;typedef NS_ENUM(NSInteger, RunDirectionType) { LeftType = 0, RightType = 1,};@protocol LGJAutoRunLabelDelegate <NSObject>@optional- (void)operateLabel: (LGJAutoRunLabel *)autoLabel animationDidStopFinished: (BOOL)finished;@end@interface LGJAutoRunLabel : UIView@property (nonatomic, weak) id <LGJAutoRunLabelDelegate> delegate;@property (nonatomic, assign) CGFloat speed;@property (nonatomic, assign) RunDirectionType directionType;- (void)addContentView: (UIView *)view;- (void)startAnimation;- (void)stopAnimation;
定義一個NS_ENUM用來判斷自動滾動的方向,分別是左和右,聲明一個可選類型的協議,用來在controller中調用并對autoLabel進行操作。聲明對外的屬性和方法。這里一目了然,主要的實現思路都集中在.m文件中。
3、.m文件
聲明“私有”變量和屬性:
@interface LGJAutoRunLabel()<CAAnimationDelegate>{ CGFloat _width; CGFloat _height; CGFloat _animationViewWidth; CGFloat _animationViewHeight; BOOL _stoped; UIView *_contentView;//滾動內容視圖}@property (nonatomic, strong) UIView *animationView;//放置滾動內容視圖@end
初始化方法:
- (instancetype)initWithFrame:(CGRect)frame { if (self == [super initWithFrame:frame]) { _width = frame.size.width; _height = frame.size.height; self.speed = 1.0f; self.directionType = LeftType; self.layer.masksToBounds = YES; self.animationView = [[UIView alloc] initWithFrame:CGRectMake(_width, 0, _width, _height)]; [self addSubview:self.animationView]; } return self;}
將滾動內容視圖contentView添加到動畫視圖animationView上:
- (void)addContentView:(UIView *)view { [_contentView removeFromSuperview]; view.frame = view.bounds; _contentView = view; self.animationView.frame = view.bounds; [self.animationView addSubview:_contentView]; _animationViewWidth = self.animationView.frame.size.width; _animationViewHeight = self.animationView.frame.size.height;}
讓animationView上的contentView自動滾動起來的主要方法在這兒,重點來了,就是這個- (void)startAnimation
方法,看一下這個方法里面是怎么樣實現的:
- (void)startAnimation { [self.animationView.layer removeAnimationForKey:@"animationViewPosition"]; _stoped = NO; CGPoint pointRightCenter = CGPointMake(_width + _animationViewWidth / 2.f, _animationViewHeight / 2.f); CGPoint pointLeftCenter = CGPointMake(-_animationViewWidth / 2, _animationViewHeight / 2.f); CGPoint fromPoint = self.directionType == LeftType ? pointRightCenter : pointLeftCenter; CGPoint toPoint = self.directionType == LeftType ? pointLeftCenter : pointRightCenter; self.animationView.center = fromPoint; UIBezierPath *movePath = [UIBezierPath bezierPath]; [movePath moveToPoint:fromPoint]; [movePath addLineToPoint:toPoint]; CAKeyframeAnimation *moveAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"]; moveAnimation.path = movePath.CGPath; moveAnimation.removedOnCompletion = YES; moveAnimation.duration = _animationViewWidth / 30.f * (1 / self.speed); moveAnimation.delegate = self; [self.animationView.layer addAnimation:moveAnimation forKey:@"animationViewPosition"];}