Skip to content

Instantly share code, notes, and snippets.

@rijieli
Created March 30, 2022 11:41
Show Gist options
  • Save rijieli/bbe4cb110d3fa34f42f10a9cd6272758 to your computer and use it in GitHub Desktop.
Save rijieli/bbe4cb110d3fa34f42f10a9cd6272758 to your computer and use it in GitHub Desktop.
Sketch drop shadow effect to iOS Swift Code.
import Foundation
import UIKit
struct DropShadowStyle {
var color: UIColor = .black
var alpha: Float = 0.1
let x: CGFloat
let y: CGFloat
let blur: CGFloat
let spread: CGFloat
let cornerRadius: CGFloat
func applyToLayer(layer: CALayer, shouldRasterize: Bool = false) {
layer.masksToBounds = false
layer.cornerRadius = cornerRadius
layer.shadowColor = color.cgColor
layer.shadowOpacity = alpha
layer.shadowOffset = CGSize(width: x, height: y)
layer.shadowRadius = blur / 2.0
if spread == 0 {
// Code below can custom corner position.
// self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: .allCorners, cornerRadii: cornerRadii).cgPath
layer.shadowPath = UIBezierPath(roundedRect: layer.bounds, cornerRadius: cornerRadius).cgPath
} else {
let offset = -(spread)
let rect = layer.bounds.insetBy(dx: offset, dy: offset)
layer.shadowPath = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).cgPath
}
if shouldRasterize {
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
}
}
// TODO: this is not a elegant way to configure shadow
// TestCase: weekHeaderShadowStyle.applyToLayer(layer: weekInfiniteSlideView.layer) not working.
func attach(_ mainView: UIView, below targetView: UIView, shadowView: UIView) {
shadowView.bounds = targetView.bounds
shadowView.frame.origin = .zero
self.applyToLayer(layer: shadowView.layer, shouldRasterize: true)
if !shadowView.isDescendant(of: mainView) {
mainView.insertSubview(shadowView, belowSubview: targetView)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment