如何应用阴影,圆角,图像和高斯模糊?

时间:2018-08-23 08:24:23

标签: swift user-interface

我需要什么:

enter image description here

我所拥有的:

enter image description here

这是我当前的代码:

class SchedulerSummaryCell: UITableViewCell {
   @IBOutlet weak var oneMileV: UIView! {
      didSet {
        oneMileV.backgroundColor = .clear
        let blurEffect = UIBlurEffect(style: .light)
        let blurView = UIVisualEffectView(effect: blurEffect)
        blurView.translatesAutoresizingMaskIntoConstraints = false
        oneMileV.insertSubview(blurView, at: 0)
        makeCircular(oneMileV)
        NSLayoutConstraint.activate([
            blurView.heightAnchor.constraint(equalTo: oneMileV.heightAnchor),
            blurView.widthAnchor.constraint(equalTo: oneMileV.widthAnchor),
            blurView.leadingAnchor.constraint(equalTo: oneMileV.leadingAnchor),
            blurView.topAnchor.constraint(equalTo: oneMileV.topAnchor)
            ])
        oneMileV.layer.applySketchShadow(alpha: 0.5, y: 4, blur: 10)

    }
  }
}

(帮助)

extension CALayer {
  func applySketchShadow(
    color: UIColor = .black,
    alpha: Float = 0.16,
    x: CGFloat = 0,
    y: CGFloat = 3,
    blur: CGFloat = 6,
    spread: CGFloat = 0)
 {
    masksToBounds = false
    shadowColor = color.cgColor
    shadowOpacity = alpha
    shadowOffset = CGSize(width: x, height: y)
    shadowRadius = blur / 2.0
    if spread == -1 {return}
    if spread == 0 {
        shadowPath = nil
    } else {
        let dx = -spread
        let rect = bounds.insetBy(dx: dx, dy: dx)
        shadowPath = UIBezierPath(rect: rect).cgPath
    }
  }
}

当我注释掉applySketchShadow代码时,我得到了:

enter image description here


问题

为什么高斯模糊消除圆角?

我是否可以同时应用圆角和高斯模糊?

然后我应该如何添加图像?

2 个答案:

答案 0 :(得分:1)

您必须将UIImageView作为子视图添加到UIViewUIView将负责阴影,UIImageView将负责处理圆角。不幸的是,您无法直接在UIImageView上添加阴影,因为您需要启用clipsToBounds = true来防止视图显示超出其边界的内容。但是,这对于显示阴影是必需的。

这将完成工作:

let shadowView = UIView()
shadowView.backgroundColor = .clear
shadowView.layer.shadowColor = UIColor.black.cgColor
shadowView.layer.shadowOffset = CGSize(width: 0.1, height: 1)
shadowView.layer.shadowRadius = 8
shadowView.layer.shadowOpacity = 0.14
shadowView.layer.masksToBounds = false

let imageView = UIImageView()
imageView.image = UIImage(named: "YourImage")
imageView.clipsToBounds = true
imageView.layer.cornerRadius = imageView.frame.width / 2
shadowView.addSubview(imageView)

答案 1 :(得分:0)

对于阴影效果,使用此扩展会有所帮助。

extension UIImageView {
    func addShadow() {
        self.layer.shadowColor = UIColor.black.cgColor
        self.layer.shadowOffset = CGSize(width: 2, height: 5)
        self.layer.shadowOpacity = 0.5
        self.layer.shadowRadius = 1.0
        self.clipsToBounds = false
    }
}