【问题标题】:CALayer - How do I create an image with a solid background and transparent text?CALayer - 如何创建具有纯色背景和透明文本的图像?
【发布时间】:2014-03-13 05:23:40
【问题描述】:

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

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

我搜索了大多数关于 calayer mask 的文章,但没有任何帮助。 我认为这篇文章 (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]
  • 对不起,我错过了写那行。它已经存在了,我刚刚对其进行了编辑。

标签: ios uiview calayer transparent avurlasset


【解决方案1】:

蒙版使用 Alpha 通道来确定要屏蔽哪些部分以及要保留哪些部分。但是,您渲染到图像中的标签被渲染为白色背景上的黑色文本,因此图像中没有透明度。

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

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

【讨论】:

  • 我试过你的方法,但它显示相反的结果 - 即黑色标题和透明背景。但我需要的是透明的标题和黑色的背景。
  • 所以你的问题并不是真正的“CALayer 掩码不适用于另一个 CALayer”。它是“如何创建具有纯色背景和透明文本的图像?”,对吗?
  • 也许你是对的。我的问题标题错误。
  • @Richard 不管怎样,我想这是缺少的部分:"Crop letter from image using Masking"
猜你喜欢
  • 1970-01-01
  • 2012-07-26
  • 2014-04-29
  • 2017-06-25
  • 1970-01-01
  • 2015-12-04
  • 2011-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多