需求:需要給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];