Sunday, October 30, 2016

Drop Shadow on a UIView

Minimum Code

Views already have a black, three point drop shadow by default but you cannot see it because the opacity is set to zero.
 
myView.layer.shadowOpacity = 1
 
That all you need to get started to show the drop shadow.

Options

Reposition the Drop Shadow

 
// Reposition the drop shadow (center it with with CGSize.zero)
myView.layer.shadowOffset = CGSize.zero // Default is (0, -3)
 
 
myView.layer.shadowOffset = CGSize(width: 0, height: -5) // Top
myView.layer.shadowOffset = CGSize(width: 5, height: 0) // Right
myView.layer.shadowOffset = CGSize(width: 0, height: 5) // Bottom
myView.layer.shadowOffset = CGSize(width: -5, height: 0) // Left
myView.layer.shadowOffset = CGSize(width: 5, height: -5) // Top, Right
myView.layer.shadowOffset = CGSize(width: -5, height: -5) // Top, Left
myView.layer.shadowOffset = CGSize(width: 5, height: 5) // Bottom, Right
myView.layer.shadowOffset = CGSize(width: -5, height: 5) // Bottom, Left
 

Change Drop Shadow Size

 
// Increase the size of the drop shadow
myView.layer.shadowRadius = 6 // Default is 3
 

Change Drop Shadow Color

 
myView.layer.shadowColor = UIColor.blue.cgColor
 

Improve Performance

 
// Apple says: "...this property will usually 
//             improve rendering performance..."
myView.layer.shadowPath = UIBezierPath(rect: myView.bounds).cgPath

// Another way is to convert the drop shadow into a bitmap.
// Apple says: "...may attempt to cache and reuse..."
myView.layer.shouldRasterize = true
 

(Xcode 8, Swift 3.0)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

SwiftUI Search & Filter with Combine - Part 3 (iOS, Xcode 13, SwiftUI, 2...

In part 3 of the Searchable video series, I show you how to use Combine in #SwiftUI for the search and filter logic connected to the searcha...