Search code examples
iosswiftuilabel

How to make a drop shadow effect on a label in Swift?


I can't figure out how to code a drop shadow on a label. I have a score label that changes so just photoshopping text with shadows wont be possible. I need to code it so it automatically has a blurry shadow behind the text at all times. Can anyone come with some examples or help?


People saying this is a duplicate, the "duplicate" is about drop shadows on UIView, mine is about UILabel. It's not the same thing.


Solution

  • Give this a try - you can run it directly in a Playground page:

    import UIKit
    import PlaygroundSupport
    
    let container = UIView(frame: CGRect(x: 0, y: 0, width: 600, height: 400))
    
    container.backgroundColor = UIColor.lightGray
    
    PlaygroundPage.current.liveView = container
    
    var r = CGRect(x: 40, y: 40, width: 300, height: 60)
    
    let label = UILabel(frame: r)
    label.font = UIFont.systemFont(ofSize: 44.0)
    label.textColor = .white
    label.frame = r
    label.text = "Hello Blur"
    
    container.addSubview(label)
    
    label.layer.shadowColor = UIColor.black.cgColor
    label.layer.shadowRadius = 3.0
    label.layer.shadowOpacity = 1.0
    label.layer.shadowOffset = CGSize(width: 4, height: 4)
    label.layer.masksToBounds = false
    

    Play around with different values for the shadow Color, Opacity, Radius and Offset

    Result:

    enter image description here