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

简介:

使用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

目录
相关文章
UIImageView加上圆角
UIImageView加上圆角
40 0
UIView添加圆角边框
UIView添加圆角边框
61 0
UITextView设置边框
UITextView设置边框
46 0
UIWebView 自适应高度
UIWebView 自适应高度
36 0
UILabel 调整行间距
UILabel 调整行间距
57 0
UIImageView 图片自适应大小
UIImageView 图片自适应大小
106 0
|
UED 缓存 异构计算
UIImageView添加圆角的几种方法
喜欢我的可以关注收藏我的个人博客:RobberJJ 创建一个UIImageView对象: UIImageView * poImgView = [[UIImageView alloc] init]; 第一种方法 poImgView.
943 0