A developer who can’t reproduce the designer’s vision is not a qualified page designer.

Sketch is the magic tool of APP design, and most designers choose it as the design tool of APP interface.

Set a shadow in Sketch with the following renderings and parameters:

(Effect in Sketch)

(Shadow parameter in Sketch)

The development of implementation

The way to do that in iOS is to use the Layer property of UIView.

The shadow-related Settings in layer are the following properties:

  • shadowPath
  • shadowColor
  • shadowOpacity
  • shadowOffset
  • shadowRadius

The corresponding relationship with the shadow parameter in Sketch is:

  • ShadowPath ~> Shadow range
  • ShadowColor ~> shadowColor
  • ShadowOpacity ~> The opacity of the shadow
  • ShadowOffset ~> X and Y
  • ShadowRadius ~> Shadow blur
(Mapping between Layer attribute and Sketch shadow)

ShadowView (size: 100×100)

let layer = shadowView.layer
// Spread corresponds to the "spread" of the shadow in Sketch, which is 10
let spread: CGFloat = 10
var rect = CGRect(x: 0, y: 0, width: 100, height: 100);
rect = rect.insetBy(dx: -spread, dy: -spread)

layer.shadowPath = UIBezierPath(rect: rect).cgPath
// The color is black (#000000)
layer.shadowColor = UIColor.black.cgColor
// alpha 50
layer.shadowOpacity = 0.5
// X: 0 Y: 10
layer.shadowOffset = CGSize(width: 0, height: 10)
// Corresponding to the "blur" setting of the shadow in Sketch, the value is 20/2 = 10
layer.shadowRadius = 10
Copy the code

The above code runs as follows:

(Effect)

100% true Sketch design, perfect.

It is worth mentioning that layer shadows and rounded corners can coexist, and the shadow path also needs to take rounded corners into account.

Add an extension to CALayer to set shadows for ease of use:

extension CALayer {
    func skt_setShadow(color: UIColor? = .black,
                       alpha: CGFloat = 0.5,
                       x: CGFloat = 0, y: CGFloat = 2,
                       blur: CGFloat = 4,
                       spread: CGFloat = 0) {
        shadowOffset = CGSize(width: x, height: y)
        shadowRadius = blur * 0.5shadowColor = color? .cgColor shadowOpacity =Float(alpha)

        let rect = bounds.insetBy(dx: -spread, dy: -spread)
        let path = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius)
        shadowPath = path.cgPath
    }
}
Copy the code

It’s easy to use, just pass in the same value as the shadow parameter in Sketch:

layer.skt_setShadow(color: .black, alpha: 0.5,
                    x: 0, y: 10, 
                    blur: 20, 
                    spread: 10)
Copy the code