简体   繁体   中英

How To Add Border To a UIView With Mask?

Here's what I need to do to my two buttons.

在此处输入图片说明

and here's what I got right now.

在此处输入图片说明

What I'm doing: - Set these up in IB inside a stackView. - Add masks - Add borders with width and color - Add shadow.

The borders are being added but being cut-off as well by the masks.

Codes:

public func addCornerRadiusToCorners(
    _ corners: UIRectCorner,
    cornerRadius: CGFloat,
    borderColor: UIColor,
    borderWidth: CGFloat) {

    //        self.layer.masksToBounds = true
    //        self.clipsToBounds = true
    self.layer.borderWidth = borderWidth
    self.layer.borderColor = borderColor.cgColor

    let size = CGSize(width: cornerRadius, height: cornerRadius)
    let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: size)
    let mask = CAShapeLayer()
    mask.path = path.cgPath
    self.layer.mask = mask

}

public func addDefaultShadow() {
    let shadowPath = UIBezierPath(rect: self.bounds)

    self.layer.masksToBounds = false
    self.layer.shadowOffset = CGSize(width: 1, height: 1)
    self.layer.shadowOpacity = 0.5
    self.layer.shadowPath = shadowPath.cgPath
}

Any idea how to achieve the result in the first photo?

EDIT: the border is being cut, the result was just got from the UI Debugger of Xcode. Sorry.

Add corner radius to you view on viewDidAppear

@IBOutlet weak var segmentView: UIView!

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    segmentView.layer.cornerRadius = segmentView.frame.size.height/2;
    segmentView.layer.borderWidth = 1.0;
    segmentView.clipsToBounds = true

    segmentView.layer.borderColor = UIColor.lightGray.cgColor

    segmentView.layer.shadowColor = UIColor.black.cgColor
    segmentView.layer.shadowOpacity = 0.2
    segmentView.layer.shadowRadius = 10.0
    segmentView.layer.shadowOffset = CGSize(width: 1, height: 1)
    segmentView.layer.masksToBounds = false
}

Sample Output:

在此处输入图片说明

您忘了剪辑视图。

self.clipsToBounds = true

您需要将maskstobounds设置为视图层

 segmentView.layer.masksToBounds = true

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