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

3

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

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

我搜索了大多数关于calayer蒙版的文章,但没有什么能帮助我。我认为这篇文章(How to make only the part covered by text/title transparent in a UIView in IOS)是有用的,并像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作为标题背景(黑色背景),但实际看到的是白屏。

有人能帮我解决吗?提前感谢。


我认为您忘记添加蒙版图层了?[self.view.layer addSublayer: animatedTitleLayer] - Mani
抱歉,我漏掉了那行代码。它已经存在了,我刚刚编辑过了。 - Alex
1个回答

1
该掩码使用Alpha通道来确定要遮罩和保留的部分。但是,您呈现为图像的标签以黑色文本在白色背景上呈现,因此图像中没有透明度。
您还指定了用于呈现图像的图形上下文是不透明的,因此即使标签的背景颜色是清晰的,您仍将获得不透明的图像。
因此,您需要在标签上设置清晰的背景颜色,并在创建图形上下文时将第二个参数传递为NO

我尝试了你的方法,但是它显示出相反的结果——即黑色标题和透明背景。但是我需要的是透明标题和黑色背景。 - Alex
所以你的问题并不是“CALayer蒙版无法与另一个CALayer一起使用”,而是“我如何创建一个具有纯色背景和透明文本的图像?”,对吗? - David Rönnqvist
也许你是对的。我给我的问题起了一个错误的标题。 - Alex
@Richard 无论如何,我猜这就是缺失的部分:"使用遮罩从图像中裁剪字母" - David Rönnqvist

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接