view添加阴影无效

需求:需要给cell里的imageview添加阴影

问题:按照标准的代码添加阴影,然并卵:代码如下:

    imageview.layer.shadowColor = [[UIColor blackColor] CGColor];
    imageview.layer.shadowOffset = CGSizeMake(4.0f, 4.0f);
    imageview.layer.shadowRadius = 4.0;
    imageview.layer.shadowOpacity = 0.5;

后谷歌说要加一句:

imageview.layer.masksToBounds = NO;,因为阴影是在imagview的layer外面画的

这样阴影出来了,然而,由于允许子元素超出父元素,所以图片的大小就不一样了

 

因此歪果仁提出了一个办法,创建两层view,内层view是imageview,不允许超出边界,外层view是shadowview,ref:

http://www.innofied.com/implementing-shadow-ios/(这个是为了解决圆角view+阴影的问题)

代码:

//注意这个layer一定添加在imageview被add后面
CALayer *sublayer = [[CALayer layer]initWithLayer:self.imageView.layer]; UIView * shadow = [[UIView alloc] initWithFrame:self.imageView .frame]; shadow.userInteractionEnabled = NO; // Modify this if needed shadow.layer.shadowColor = [[UIColor blackColor] CGColor]; shadow.layer.shadowOffset = CGSizeMake(4.0f, 4.0f); shadow.layer.shadowRadius = 4.0; shadow.layer.masksToBounds = NO; //关键 shadow.clipsToBounds = NO; shadow.layer.shadowOpacity = 0.5; [ self.imageView.superview insertSubview:shadow belowSubview: self.imageView]; [shadow addSubview:self.imageView];

 

posted @ 2016-09-07 18:19  伟大的臭猪猪  阅读(2726)  评论(0编辑  收藏  举报