文档章节

IOS使用AVFoundation在视频上添加字幕以及控制字幕时间

aron1992
 aron1992
发布于 2017/02/04 16:20
字数 885
阅读 332
收藏 0

IOS在视频上添加字幕效果的基本思路是:

  1. 使用自定义的CATextLayer文字图层或者CAShapeLayer文字图层,添加到视频的Layer上创建用户自定义的字幕效果。这两者的区别是:CATextLayer支持设置简单的文字效果,包括文字的内容、字体、字号大小、对其方式、文字颜色、背景颜色等基本的属性;CAShapeLayer功能更强大,提供了CATextLayer没有的边框大小、边框颜色等设置,如果需要更高级的文字内容展示,需要使用CATextLayer配合UIBezierPath来定制自定义的文字内容。

  2. 通过设置Layer图层的动画来控制字幕的时间点和时间长度,这里有一个坑如果单独设置CATextLayer或者CAShapeLayer的动画不能控制开始的时间,需要额外添加一个CALayer图层,把文字图层CATextLayer或者CAShapeLayer添加到父CALayer图层中,在文字图层CATextLayer或者CAShapeLayer上设置开始的动画

    NSTimeInterval animatedInStartTime = startTime + initAnimationDuration;
    CABasicAnimation *fadeInAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeInAnimation.fromValue = @0.0f;
    fadeInAnimation.toValue = @1.0f;
    fadeInAnimation.additive = NO;
    fadeInAnimation.removedOnCompletion = NO;
    fadeInAnimation.beginTime = animatedInStartTime;
    fadeInAnimation.duration = animationDuration;
    fadeInAnimation.autoreverses = NO;
    fadeInAnimation.fillMode = kCAFillModeBoth;
    [textLayer addAnimation:fadeInAnimation forKey:@"opacity"];

在父CALayer图层上设置结束的动画,这样设置才能实现用户自定义的时间点和时间长度

NSTimeInterval animatedOutStartTime = startTime + duration - animationDuration;
    CABasicAnimation *fadeOutAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeOutAnimation.fromValue = @1.0f;
    fadeOutAnimation.toValue = @0.0f;
    fadeOutAnimation.additive = NO;
    fadeOutAnimation.removedOnCompletion = NO;
    fadeOutAnimation.beginTime = animatedOutStartTime;
    fadeOutAnimation.duration = animationDuration;
    fadeOutAnimation.autoreverses = NO;
    fadeOutAnimation.fillMode = kCAFillModeBoth;
    [animatedTitleLayer addAnimation:fadeOutAnimation forKey:@"opacity"];

完整的代码

- (CALayer *)buildLayerbuildTxt:(NSString*)text
                       textSize:(CGFloat)textSize
                      textColor:(UIColor*)textColor
                    strokeColor:(UIColor*)strokeColor
                        opacity:(CGFloat)opacity
                       textRect:(CGRect)textRect
                       fontPath:(NSString*)fontPath
                     viewBounds:(CGSize)viewBounds
                      startTime:(NSTimeInterval)startTime
                       duration:(NSTimeInterval)duration
{
    if (!text || [text isEqualToString:@""])
    {
        return nil;
    }
    
    // Create a layer for the overall title animation.
    CALayer *animatedTitleLayer = [CALayer layer];
    
    // 1. Create a layer for the text of the title.
    CATextLayer *titleLayer = [CATextLayer layer];
    titleLayer.string = text;
    titleLayer.font = (__bridge CFTypeRef)(@"Helvetica");
    titleLayer.fontSize = textSize;
    titleLayer.alignmentMode = kCAAlignmentCenter;
    titleLayer.bounds = CGRectMake(0, 0, textRect.size.width, textRect.size.height);
    titleLayer.foregroundColor = textColor.CGColor;
    titleLayer.backgroundColor = [UIColor clearColor].CGColor;
    // [animatedTitleLayer addSublayer:titleLayer];
    
    // 添加文字以及边框效果
    UIFont *font = nil;
    if ((fontPath != nil) && (fontPath.length > 0)) {
        font = [[FLVideoEditFontManager sharedFLVideoEditFontManager] fontWithPath:fontPath size:textSize];
        titleLayer.font = CGFontCreateWithFontName((__bridge CFStringRef)font.fontName);
    }
    if (font == nil) {
        titleLayer.font = (__bridge CFTypeRef)(@"Helvetica");
    }
    
    UIBezierPath *path = nil;
    if (font) {
        path = [FLLayerBuilderTool createPathForText:text fontHeight:textSize fontName:(__bridge CFStringRef)(font.fontName)];
    }
    else
    {
        path = [FLLayerBuilderTool createPathForText:text fontHeight:textSize fontName:CFSTR("Helvetica")];
    }
    CGRect rectPath = CGPathGetBoundingBox(path.CGPath);
    CAShapeLayer *textLayer = [CAShapeLayer layer];
    textLayer.path = path.CGPath;
    textLayer.lineWidth = 1;
    if (strokeColor != nil) {
        textLayer.strokeColor = strokeColor.CGColor;
    }
    if (textColor != nil) {
        textLayer.fillColor = textColor.CGColor;
    }
    textLayer.lineJoin = kCALineJoinRound;
    textLayer.lineCap = kCALineCapRound;
    textLayer.geometryFlipped = NO;
    textLayer.opacity = opacity;
    textLayer.bounds = CGRectMake(0, 0, rectPath.size.width, textSize+10);
    [animatedTitleLayer addSublayer:textLayer];
    
    // 动画图层位置
    animatedTitleLayer.position = CGPointMake(textRect.origin.x+textRect.size.width/2, viewBounds.height - textRect.size.height/2 - textRect.origin.y);
    
    NSTimeInterval initAnimationDuration = 0.1f;
    NSTimeInterval animationDuration = 0.1f;
    
    // 3.显示动画
    NSTimeInterval animatedInStartTime = startTime + initAnimationDuration;
    CABasicAnimation *fadeInAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeInAnimation.fromValue = @0.0f;
    fadeInAnimation.toValue = @1.0f;
    fadeInAnimation.additive = NO;
    fadeInAnimation.removedOnCompletion = NO;
    fadeInAnimation.beginTime = animatedInStartTime;
    fadeInAnimation.duration = animationDuration;
    fadeInAnimation.autoreverses = NO;
    fadeInAnimation.fillMode = kCAFillModeBoth;
    [textLayer addAnimation:fadeInAnimation forKey:@"opacity"];
    
    NSTimeInterval animatedOutStartTime = startTime + duration - animationDuration;
    CABasicAnimation *fadeOutAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeOutAnimation.fromValue = @1.0f;
    fadeOutAnimation.toValue = @0.0f;
    fadeOutAnimation.additive = NO;
    fadeOutAnimation.removedOnCompletion = NO;
    fadeOutAnimation.beginTime = animatedOutStartTime;
    fadeOutAnimation.duration = animationDuration;
    fadeOutAnimation.autoreverses = NO;
    fadeOutAnimation.fillMode = kCAFillModeBoth;
    
    [animatedTitleLayer addAnimation:fadeOutAnimation forKey:@"opacity"];
    
    return animatedTitleLayer;
}

依赖的工具类FLLayerBuilderTool.m文件:

#import "FLLayerBuilderTool.h"
#import <CoreText/CoreText.h>

@implementation FLLayerBuilderTool


+ (UIBezierPath*) createPathForText:(NSString*)string fontHeight:(CGFloat)height fontName:(CFStringRef)fontName
{
    if ([string length] < 1)
        return nil;
    
    UIBezierPath *combinedGlyphsPath = nil;
    CGMutablePathRef letters = CGPathCreateMutable();
    
    CTFontRef font = CTFontCreateWithName(fontName, height, NULL);
    if (font == nil) {
        font = (__bridge CFTypeRef)(@"Helvetica");
    }
    NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:
                           (__bridge id)font, kCTFontAttributeName,
                           nil];
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:string
                                                                     attributes:attrs];
    CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)attrString);
    CFArrayRef runArray = CTLineGetGlyphRuns(line);
    
    // for each RUN
    for (CFIndex runIndex = 0; runIndex < CFArrayGetCount(runArray); runIndex++)
    {
        // Get FONT for this run
        CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runArray, runIndex);
        CTFontRef runFont = CFDictionaryGetValue(CTRunGetAttributes(run), kCTFontAttributeName);
        
        // for each GLYPH in run
        for (CFIndex runGlyphIndex = 0; runGlyphIndex < CTRunGetGlyphCount(run); runGlyphIndex++)
        {
            // get Glyph & Glyph-data
            CFRange thisGlyphRange = CFRangeMake(runGlyphIndex, 1);
            CGGlyph glyph;
            CGPoint position;
            CTRunGetGlyphs(run, thisGlyphRange, &glyph);
            CTRunGetPositions(run, thisGlyphRange, &position);
            
            // Get PATH of outline
            {
                CGPathRef letter = CTFontCreatePathForGlyph(runFont, glyph, NULL);
                CGAffineTransform t = CGAffineTransformMakeTranslation(position.x, position.y);
                CGPathAddPath(letters, &t, letter);
                CGPathRelease(letter);
            }
        }
    }
    CFRelease(line);
    
    combinedGlyphsPath = [UIBezierPath bezierPath];
    [combinedGlyphsPath moveToPoint:CGPointZero];
    [combinedGlyphsPath appendPath:[UIBezierPath bezierPathWithCGPath:letters]];
    
    CGPathRelease(letters);
    CFRelease(font);
    
    if (attrString)
    {
        attrString = nil;
    }
    
    return combinedGlyphsPath;
}

@end

参考资料:
视频特效制作:如何给视频添加边框、水印、动画以及3D效果
视频特效制作2
AVFoundation Tutorial: Adding Overlays and Animations to Videos

© 著作权归作者所有

aron1992

aron1992

粉丝 59
博文 87
码字总数 159227
作品 0
厦门
程序员
私信 提问
iOS/安卓全能视频播放器推荐

前言 前几天有朋友下载了些 ts 格式的高清电视剧,但是没法在 iPad(iOS) 上播放,只好先在电脑上转换成 MP4 格式,转换起来很花时间,结果也不如意。 其实现在各平台都有全格式支持的播放器,...

己立
2018/07/22
0
0
ijkplayer k0.7.6 发布,Bilibili 开源视频播放器

ijkplayer k0.7.6 发布了,ijkplayer 是 Bilibili 开源的一个基于 ffplay 的轻量级 Android/iOS 视频播放器。实现了跨平台功能,API易于集成;编译配置可裁剪,方便控制安装包大小;支持硬件...

王练
2017/01/06
5.7K
18
HTML5游戏开发高级教程 | Lynda教程 中文字幕

HTML5游戏开发高级教程 | Lynda教程 中文字幕 Advanced HTML5 Game Development 课程ID: 597988 时长: 2.3小时 所属类别:Html 全部游戏开发课程 了解如何使用HTML5创建交互式,动态和丰富多彩...

zwsub
2018/08/04
0
0
简单介绍一个开发***的三方库吧,NEKit(swift)

因为最近上架了一个SkimTumblog需要链接*,所以对的需求很大。于是就想自己做一个**的iOS客户端。于是就开始Google,找到了以为大神开发的三方库,目前为止1.2k个star,支持iOS和macOS,功能...

笙语亦凉
2018/06/21
0
0
AVFoundation | 封装一个好用的视频播放器

一:简介 AVFoundation是苹果在iOS和OS X系统中用于处理基于时间的媒体数据的Objective-C框架. 供使用者来开发媒体类型的应用程序。 上图是iOS系统下媒体应用的结构层. AVKit框架用于简化媒体...

展菲
03/06
0
0

没有更多内容

加载失败,请刷新页面

加载更多

spring 本类中方法调用另外一个方法事务不生效

1、在spring配置文件中添加 <aop:aspectj-autoproxy expose-proxy="true"/> 声明自动代理 2、AopContext.currentProxy()来获取代理类 3、使用代理类proxy进行代理调用内部声明了事务的方法 ......

重城重楼
32分钟前
5
0
项目 banner 乱弹

------------------------------------------ 村上春树 ------------------------------------- 如果我爱你,而你也正巧爱我,你头发乱了的时候,我会笑笑地替你拨一拨,然后手还留恋地在你...

宿小帅
44分钟前
3
0
PHP获取未来七天的日期和星期

php获取未来七天的日期和星期代码 第一步:获取需要天数的日期,然后调用函数 //获取未来七天的日期 for($i=1;$i<8;$i++){ $dateArray[$i]=date('Y-m-d',strtotime(d...

一只懒猫-
55分钟前
2
0
总结:IO模型

分类 多路复用 参考文章: https://www.jianshu.com/p/6a6845464770 https://www.cnblogs.com/zingp/p/6863170.html https://blog.csdn.net/sehanlingfeng/article/details/78920423......

浮躁的码农
58分钟前
2
0
fabric-sdk-java 1.4安装说明

Hyperledger Fabric Java SDK是开发基于Hyperledger Fabric区块链的Java应用之必备开发包。本文将介绍如何在Maven、Gradle和Eclipse中安装使用最新1.4版本的Hyperledger Fabric Java SDK。 ...

汇智网教程
今天
2
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部