https://github.com/YouXianMing

使用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
复制代码

 

 

 

 

 

 

 

posted @   YouXianMing  阅读(4359)  评论(1编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示