Draw shadow only from 3 sides of UIView

后端 未结 4 1157
夕颜
夕颜 2020-12-07 19:13

I\'ve successfully implemented drawing a shadow around my UIView like this:

block1.layer.masksToBounds = NO;
block1.layer.shadowOffset = CGSizeM         


        
4条回答
  •  北海茫月
    2020-12-07 19:38

    Updating Ryan Poolos Answer to Swift 3.0

    Thanks to Ryan Poolos

    class sampleViewController: UIViewController {
        var block1: UIView! = nil
    
        override func viewDidLoad() {
    
            super.viewDidLoad()
            block1 = UIView(frame: CGRect(x: 32.0, y: 32.0, width: 128.0, height: 128.0))
            block1.backgroundColor = UIColor.orange
            self.view.addSubview(block1)
    
            block1.layer.masksToBounds = false
            block1.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
            block1.layer.shadowRadius = 1.0
            block1.layer.shadowOpacity = 0.7
    
            let path = UIBezierPath()
    
            // Start at the Top Left Corner
            path.move(to: CGPoint(x: 0.0, y: 0.0))
    
            // Move to the Top Right Corner
            path.addLine(to: CGPoint(x: block1.frame.size.width, y: 0.0))
    
            // Move to the Bottom Right Corner
            path.addLine(to: CGPoint(x: block1.frame.size.width, y: block1.frame.size.height))
    
            // This is the extra point in the middle :) Its the secret sauce.
            path.addLine(to: CGPoint(x: block1.frame.size.width/2.0, y: block1.frame.size.height/2.0))
    
            // Move to the Bottom Left Corner
            path.addLine(to: CGPoint(x: 0.0, y: block1.frame.size.height))
    
            path.close()
    
            block1.layer.shadowPath = path.cgPath
        }
    }
    

    Result:

提交回复
热议问题