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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值