【问题标题】:CALAYER apply background color plus pattern imageCALAYER 应用背景颜色加图案图像
【发布时间】:2014-12-28 14:20:42
【问题描述】:

我很喜欢 Core Animation 的东西。 我需要将图案图像应用到 CALAyer。 这部分与类似的东西完美配合:

color = UIColor(patternImage: UIImage(named: "myPatternImage")! 
shapeLayer.fillColor = color.CGColor;

但现在我需要在图案后面应用背景颜色。我的 Patter 图像是 png (带有 alpha 组件)。 所以我想在形状上应用一个简单的颜色,然后应用图案图像。 有没有办法即时做到这一点?

【问题讨论】:

  • 我正在为这些图层设置动画。如果我理解您的评论,您的意思是我可以在我的真实图层之上使用“克隆”图层。但是因为我要为我的图层设置动画,所以我也必须为克隆图层设置动画;它会变得非常复杂。所以我更喜欢使用基于子层的解决方案..但我没有达到使其工作。
  • 我对克隆层只字未提。我说使用两个单独的层。下面的答案是正确的。

标签: ios objective-c swift core-animation calayer


【解决方案1】:

只需添加另一个具有背景颜色的子图层并将其添加到您的图案背景图层之前:

UIColor *backgroundColor = [UIColor redColor];
CALayer *solidBackgroundColorLayer = [[CALayer alloc] init];
solidBackgroundColorLayer.backgroundColor = backgroundColor.CGColor;
[[self layer] addSublayer:solidBackgroundColorLayer];
UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"MyPattern.png"]];
backgroundLayer = [[CALayer alloc] init];
[backgroundLayer setBackgroundColor:[color CGColor]];
[[self layer] addSublayer:backgroundLayer];

【讨论】:

  • 抱歉,我的问题有误。我放了错误的代码。我没有使用背景颜色属性,而是使用 fillColor 属性。因为我的 CALayers 里面有 uibezierPath。 (我正在使用 SVGKit)。所以我根据你的回答尝试了一些东西: var solidBackgroundLayer = CAShapeLayer(layer: shapeLayer); solidBackgroundLayer.fillColor = color.CGColor; shapeLayer.addSublayer(solidBackgroundLayer);但它没有用
  • fillColor在形状层中设置路径的填充颜色,但是你没有用任何路径设置solidBackgroundLayer.path...
  • 啊,谢谢,我虽然是 CAShapeLayer(layer: shapeLayer);会将 shapeLayer 中的所有属性复制到新的属性,但它没有复制路径。非常感谢,现在它工作正常。但我有点担心性能:)
  • @LastMove initWithLayer: 用于创建图层的阴影副本,通常在presentationLayer 上的动画期间使用。调用这个方法来复制你的图层是完全错误的。创建新图层并手动设置路径。所有这些都在您应该开始阅读的文档中描述。
  • 是的,我明白这一点。顺便说一句,我没有使用这个解决方案。由于我制作了很多动画,因此会导致 FPS 下降。最后,我结合颜色和 UIImage 来创建一个新的 UIImage,我可以直接将其作为模式应用。它提供了更好的性能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-14
  • 2012-01-01
  • 2013-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多