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

标签 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


问题

为什么高斯模糊会抵消圆角?

有没有办法让我同时应用圆角和高斯模糊?

我应该如何添加图像?

最佳答案

您必须将 UIImageView 作为 subview 添加到 UIView 中。 UIView 将负责阴影,UIImageView 将负责圆角。不幸的是,您无法直接向 UIImageView 添加阴影,因为您需要启用 clipsToBounds = true 以防止 View 显示其边界之外的内容。然而,这是显示阴影所必需的。

这将完成工作:

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)

关于swift - 如何应用阴影、圆角、图像和高斯模糊?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51981313/

相关文章:

java - 没有默认按钮的 JDialog

java - 我正在尝试在一个简单的银行系统上实现 'undo' JButton,它将撤消上次执行的操作

ios - 我有一个场景,我想添加3天/5天吃药的通知。根据用户要求进行提醒

ios - 我如何访问 SWRevealViewController 表单元以便我可以执行SegueWithIdentifier

arrays - SWIFT - 如何获取数组的类型?

java - 代号一,操作事件不起作用 - 需要解释

java - 如何使用 Java Swing 实现可拖动选项卡?

matlab - 如何手动将 Matlab GUIDE GUI 代码转换为 Octave UI 组件

swift - Swift 3 中预期参数类型 UnsafeMutablePointer<_> 的 UnsafeMutablePointer

swift - UIAlertView 不在窗口层次结构中