将阴影添加到图层

时间:2012-11-08 07:00:52

标签: ios

我可以使用以下代码为imageView图层添加阴影。

self.imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"test.png"]];
self.imageView.center = self.view.center;
CALayer *containerLayer= [CALayer layer];
containerLayer.shadowColor = [UIColor blackColor].CGColor;
containerLayer.shadowRadius = 10.0f;
containerLayer.shadowOffset = CGSizeMake(10.0f, 5.0f);
containerLayer.shadowOpacity = .8f;
[containerLayer addSublayer:self.imageView.layer];
[self.view.layer addSublayer:containerLayer];

1。问题是我不知道为什么我必须将imageView.layer添加到containerLayer以获取imageView阴影效果。但是,如果我将containerLayer添加到imageView.layer,那么imageView中没有阴影,为什么?

错误代码是:

 self.imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"test.png"]];
self.imageView.center = self.view.center;
CALayer *containerLayer= [CALayer layer];
/*same as before*/
[self.imageView.layer addSublayer:containerLayer];
[self.view.layer addSublayer:self.imageView.layer];

问题2:containerLayer(用于向imageView提供阴影)frame = {{0,0},{0,0}},但最终位置位于屏幕中心。为什么呢?

enter image description here

2 个答案:

答案 0 :(得分:2)

图层中需要一些不透明的东西才能创建阴影(除非您明确指定了shadowPath)。因此,您的第一个代码版本可以正常工作,因为containerLayer将imageView的图层作为子图层。但是,正如您在问题#2中注意到的那样,containerLayer的框架表明它实际上位于左上角,大小为(0,0)。您仍然可以看到图像的原因是containerLayer没有屏蔽其边界。将此行添加到您的第一个版本,图像将消失:

[containerLayer setMasksToBounds: YES];  // kitten (and shadow) is gone

您的代码版本#2不会显示阴影,因为在某种程度上,containerLayer不会“包含”任何内容。如果使用版本#2但为containerLayer提供新框架和不透明背景颜色,则会出现阴影。 (但这显然不是解决方案,因为图像被遮盖了......)另请注意,当图层的背景为[UIColor clearColor]时,没有阴影。

[self.imageView.layer addSublayer:containerLayer];
containerLayer.frame = self.imageView.layer.bounds;
containerLayer.backgroundColor = [UIColor yellowColor].CGColor; // yellow box w/shadow
// containerLayer.backgroundColor = [UIColor clearColor].CGColor;  // no shadow here

如果你想拥有一个带有UIImageView阴影的容器,你可以这样做:

UIView * shadowView = [[UIView alloc] initWithFrame: self.imageView.frame];
shadowView.layer.shadowColor = [UIColor blackColor].CGColor;
shadowView.layer.shadowRadius = 10.0f;
shadowView.layer.shadowOffset = CGSizeMake(10.0f, 5.0f);
shadowView.layer.shadowOpacity = .8f;
[self.view addSubview: shadowView];
self.imageView.frame = (CGRect) { CGPointZero, self.imageView.frame.size };
[shadowView addSubview: self.imageView];

可以以类似的方式使用CALayer代替UIView。或者您可以直接将阴影属性应用于imageView的图层,确保视图和图层都不会剪切/屏蔽边界。

答案 1 :(得分:-3)

如果要在图像视图上添加阴影,只需更改该图像视图的Alpha值(0.0 min - 1.0 max)。这将为您提供阴影效果,每当您想要删除阴影时,只需将alpha值恢复为1.0。

例如:

    self.imageview.alpha = 0.5 // shadow state
    self.imageview.alpha = 1.0 // original state
相关问题