使用UILabel實現滾動字幕移動效果

這個鏈接中的代碼也實現了這種效果
https://github.com/cbpowell/MarqueeLabel
最終效果如下:

原理如下:
1. 獲取文本
2. 計算文本寬度
3. 將這個Label放入ScrollView中
4. 將ScrollView的contentSize的寬度設置與文本寬度一致
5. 做動畫
*6. 邊緣的漸隱效果請使用帶透明像素的PNG圖片

// // RootViewController.m // // Copyright (c) 2014年 Y.X. All rights reserved. // #import "RootViewController.h" #import "YXKit.h" #import "FontPool.h" @interface RootViewController () @end @implementation RootViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor blackColor]; // 注冊字體 REGISTER_FONT(bundleFont(@"新蒂小丸子體.ttf"), @"新蒂小丸子體"); // 獲取文本 NSString *string = @" 喜歡這首情思幽幽的曲子,仿佛多么遙遠,在感嘆着前世的情緣,又是那么柔軟,在祈願着來世的纏綿。《蓮的心事》,你似琉璃一樣的晶瑩,柔柔地撥動我多情的心弦。我,蓮的心事,有誰知?我,蓮的矜持,又有誰懂? "; // 初始化label UILabel *label = [UILabel new]; label.text = string; label.numberOfLines = 0; label.textColor = [UIColor cyanColor]; label.font = [UIFont fontWithName:CUSTOM_FONT(@"新蒂小丸子體", 0) size:20.f]; // 計算尺寸 CGSize size = [label boundingRectWithSize:CGSizeMake(0, 0)]; label.frame = (CGRect){CGPointZero, size}; // 初始化ScrollView UIScrollView *showView = \ [[UIScrollView alloc] initWithFrame:CGRectMake(0, 90, 320, size.height)]; showView.contentSize = size; showView.showsHorizontalScrollIndicator = NO; [showView addSubview:label]; [self.view addSubview:showView]; // 形成邊緣的遮罩 UIImageView *imageView = \ [[UIImageView alloc] initWithFrame:CGRectMake(0, 90, 320, size.height)]; imageView.image = [UIImage imageNamed:@"bg"]; [self.view addSubview:imageView]; // 動畫 [UIView animateKeyframesWithDuration:10 delay:7 options:UIViewKeyframeAnimationOptionAllowUserInteraction animations:^{ // 計算移動的距離 CGPoint point = showView.contentOffset; point.x = size.width - 320.f; showView.contentOffset = point; } completion:^(BOOL finished) { }]; } @end
