有没有办法防止CALayer阴影重叠相邻的图层? [英] Is there a way to prevent CALayer shadows from overlapping adjacent layers?

查看:74
本文介绍了有没有办法防止CALayer阴影重叠相邻的图层?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 CALayers 的集合。每层都是同一父 CALayer 的子层,并且每层都有一个阴影。图层是动态定位的,并且有很多图层,因此我无法预测它们将如何提前安排。

I have a collection of CALayers. Each layer is a sublayer of the same parent CALayer, and each has a shadow applied to it. The layers are positioned dynamically, and there are many of them, so I can't predict how they'll be arranged ahead of time.

如果图层相邻 CALayers 之一的阴影彼此之间(足够接近,几乎可以触摸)在另一个 CALayer 。在大多数情况下,这可能是理想的效果,但是我希望我的图层存在于同一z平面中。 (例如,将 CSS3 阴影应用于网页设计中的块元素的方式。)

If the layers are adjacent to each other (close enough that they are almost touching) the shadow of one of the CALayers is rendered on top of the other CALayer. That's probably the desired effect in most cases, but I want my layers to exist in the same z-plane. (An example of this is the way CSS3 shadows are applied to block elements in web design.)

这可能吗?我该如何实现呢?

Is this possible? How can I achieve this?

(我有这样的想法:在每个 CALayer 中添加一个阴影子层我自己的阴影图像,然后将z位置设置为较低的值,但是层树使这不可能吗?一层坐标系中的z位置独立于另一层坐标系中的z位置,对吗? )

(I had this idea: Adding a 'shadow' sublayer to each CALayer with my own shadow image, and setting the z-position to a lower value. But doesn't the layer-tree make this impossible? Z-positions in one layer's coordinate system are independent from z-positions in another layer's coordinate system, right?)

推荐答案

如果所有阴影层都具有相同的阴影设置,请将它们放入容器层并在容器层。示例:

If all of the shadowed layers have the same shadow settings, put them into a container layer and set the shadow on the container layer. Example:

- (void)viewDidLoad
{
    [super viewDidLoad];

    CALayer *containerLayer = [CALayer layer];
    containerLayer.frame = self.view.bounds;
    containerLayer.shadowRadius = 10;
    containerLayer.shadowOpacity = 1;
    [self.view.layer addSublayer:containerLayer];

    CAShapeLayer *layer1 = [CAShapeLayer layer];
    layer1.bounds = CGRectMake(0, 0, 200, 200);
    layer1.position = CGPointMake(130, 130);
    layer1.path = [UIBezierPath bezierPathWithOvalInRect:layer1.bounds].CGPath;
    layer1.fillColor = [UIColor redColor].CGColor;
    [containerLayer addSublayer:layer1];

    CAShapeLayer *layer2 = [CAShapeLayer layer];
    layer2.bounds = CGRectMake(0, 0, 200, 200);
    layer2.position = CGPointMake(170, 200);
    layer2.path = [UIBezierPath bezierPathWithOvalInRect:layer2.bounds].CGPath;
    layer2.fillColor = [UIColor blueColor].CGColor;
    [containerLayer addSublayer:layer2];
}

输出:

这篇关于有没有办法防止CALayer阴影重叠相邻的图层?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆