如何在SWIFT3.0.1阴影中同时提供一个带有圆角的阴影

问题描述:

我想给一个imageView同时带圆角的阴影,但是我失败了。如何在SWIFT3.0.1阴影中同时提供一个带有圆角的阴影

解决方案是创建两个单独的视图。一个用于阴影,另一个用于图像本身。在imageView上clipToBounds图层,以便正确添加角半径。

将imageView放在shadowView的顶部,你已经有了解决方案!

这里是我的解决方案

基本思想:

  1. 使用额外的视图(比如AView)的图像视图的超视图(那些对你愿意有shado观点)和该视图类分配给DGShadoView
  2. 引脚图片以AView(即超级视图)由左,右,顶部和底部具有恒定5
  3. 从storybosrd的属性检查器设置回AView的底色清晰的彩色这是很重要的

里面的想法:这里我们使用的Aview几乎边境贝塞尔路径并将所有圆角属性和阴影属性设置为该路径,并且我们将我们的目标图像视图与该路径绑定在一起

@IBDesignable 
class DGShadoView:UIView { 

override func draw(_ rect: CGRect) { 
    self.rect = rect 
    decorate(rect: self.rect) 
} 

func decorate(rect:CGRect) { 


    //self.backgroundColor = UIColor.clear 
    //IMPORTANT: dont forgot to set bg color of your view to clear color from story board's property inspector 

    let ref = UIGraphicsGetCurrentContext() 
    let contentRect = rect.insetBy(dx: 5, dy: 5); 
    /*create the rounded oath and fill it*/ 
    let roundedPath = UIBezierPath(roundedRect: contentRect, cornerRadius: 5) 
    ref!.setFillColor("your color for background".cgColor) 
    ref!.setShadow(offset: CGSize(width:0,height:0), blur: 5, color: "your color for shado".cgColor) 
    roundedPath.fill() 

    /*draw a subtle white line at the top of view*/ 
    roundedPath.addClip() 
    ref!.setStrokeColor(UIColor.red.cgColor) 
    ref!.setBlendMode(CGBlendMode.overlay) 
    ref!.move(to: CGPoint(x:contentRect.minX,y:contentRect.minY+0.5)) 
    ref!.addLine(to: CGPoint(x:contentRect.maxX,y:contentRect.minY+0.5)) 
} 

}

更新

扩展方法

还有一个办法。只需用空白粘贴一个类,然后粘贴以下UIImageView扩展代码,将此子类分配给您在其上映射的ImageView。

import UIKit 

class DGShadowView: UIImageView { 

    @IBInspectable var intensity:Float = 0.2{ 
     didSet{ 
      setShadow() 
     } 
    } 
    override func layoutSubviews() 
    { 
     super.layoutSubviews() 
     setShadow() 
    } 

    func setShadow(){ 
     let shadowPath = UIBezierPath(rect: bounds) 
     layer.masksToBounds = false 
     layer.shadowColor = UIColor.black.cgColor 
     layer.shadowOffset = CGSize(width: 0.0, height: 0.3) 
     layer.shadowOpacity = intensity 
     layer.shadowPath = shadowPath.cgPath 
    } 
}