使用UILabel实现滚动字幕移动效果

使用UILabel实现滚动字幕移动效果

使用UILabel实现滚动字幕移动效果

这个链接中的代码也实现了这种效果

https://github.com/cbpowell/MarqueeLabel

 

最终效果如下:

原理如下:

1. 获取文本

2. 计算文本宽度

3. 将这个Label放入ScrollView中

4. 将ScrollView的contentSize的宽度设置与文本宽度一致

5. 做动画

*6. 边缘的渐隐效果请使用带透明像素的PNG图片

使用UILabel实现滚动字幕移动效果

//

//  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

 

 

 

 

 

 

 

你可能感兴趣的:(UILabel)