简体   繁体   中英

Swift shadow does not spread correctly

I'm been trying to create a shadow for my UIView. I looked around and found an extension for the CALayer class from this post. https://stackoverflow.com/a/48489506/9188318

So far its been working well for me until I try to put in a non 0 number for the spread.

With the spread being 0. This is the result

使用 0 点差

And here is the result using a spread of 1

使用 1 个点差

And it gets even worse with a spread of 5

使用 5 的点差

The problem that I'm having is that it doesn't have rounded corners and I have no idea how to fix this. Heres my code for the UIView that uses this view. The extension that is used to make the shadow is in the post above.

UIView code

class FileCalculateOperatorSelectionButton : UIView {

    private var isActivated : Bool = false

    //Background colors
    private var unSelectedBackgroundColor : UIColor = UIColor(red: 178/255, green: 90/255, blue: 253/255, alpha: 1.0)
    private var selectedBackgroundColor : UIColor = UIColor.white
   
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.commonInit()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        self.commonInit()
    }

    private func commonInit() {
        self.layer.cornerRadius = self.frame.height/2
        self.backgroundColor = self.unSelectedBackgroundColor
    
        let shadowColor = UIColor(red: 0xC8, green: 0xC6, blue: 0xC6)

        //Change the spread argument here
        self.layer.applySketchShadow(color: .black, alpha: 0.5, x: 0, y: 0, blur: 5, spread: 0)
    }   
}

Try setting the layer's masksToBounds property to true .

self.layer.masksToBounds = true

Change shadowPath in applySketchShadow function in CALayer extension like below;

// shadowPath = UIBezierPath(rect: rect).cgPath
shadowPath = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).cgPath 

when spread: 1

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM