繁体   English   中英

CALayer - 如何创建具有纯色背景和透明文本的图像?

[英]CALayer - How do I create an image with a solid background and transparent text?

我正在尝试使用AVComposition创建电影生成应用程序,并且在制作标题框架时遇到麻烦。 每个帧实际上是一个calayer,标题层位于其他帧的顶部。

标题(文本)需要透明,黑色背景,以便他们可以在标题文本字母下看到第一个内容框架的某些部分。

我搜索了大部分有关calayer面具的文章,但没有任何帮助我。 我认为这篇文章( 如何只在IOS中的UIView中使文本/标题覆盖的部分透明 )是有用的,并且编码像Dave的方式,但只有白屏。

这是我做的:

// create UILabel from the title text
CGRect rectFrame = CGRectMake(0, 0, videoSize.width, videoSize.height);
UILabel *lbTitle = [[UILabel alloc] initWithFrame:rectFrame];
lbTitle.text = self.titleText;
lbTitle.font = [UIFont fontWithName:@"Helvetica" size:60];
lbTitle.textColor = [UIColor blackColor];
lbTitle.backgroundColor = [UIColor whiteColor];

// get title image and create mask layer
UIGraphicsBeginImageContextWithOptions(lbTitle.bounds.size, TRUE, [[UIScreen mainScreen] scale]);
[lbTitle.layer renderInContext:UIGraphicsGetCurrentContext()];
CGImageRef viewImage = [UIGraphicsGetImageFromCurrentImageContext() CGImage];
UIGraphicsEndImageContext();

CALayer *maskLayer = [CALayer layer];
maskLayer.contents = (__bridge id)viewImage;
maskLayer.frame = rectFrame;

// create title background layer and set mastLayer as mast layer of this layer
// this layer corresponds to "UIView's layer" in Dave's method
CALayer *animatedTitleLayer = [CALayer layer];
animatedTitleLayer.backgroundColor = [UIColor whiteColor].CGColor;
animatedTitleLayer.mask = maskLayer;
animatedTitleLayer.frame = rectFrame;

...
[view.layer addSubLayer:animatedTitleLayer];

这里我使用animatedTitleLayer作为标题背景(黑色背景),但我看到的是白色屏幕。

有人可以帮帮我吗? 提前致谢。

掩码使用alpha通道来确定要屏蔽的部分以及要保留的部分。 但是,渲染到图像中的标签在白色背景上呈现为黑色文本,因此图像中没有透明度。

您还指定了用于渲染图像的图形上下文是不透明的,因此即使标签的背景颜色很清晰,您也会得到不透明的图像。

因此,您需要在标签上设置清晰的背景颜色,并在创建图形上下文时将NO作为第二个参数传递。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM