如何使用蒙版为UIView添加边框?

时间:2017-06-27 10:48:50

标签: ios objective-c swift

这是我需要对我的两个按钮做的事情。

enter image description here

这就是我现在所得到的。

enter image description here

我在做什么: - 在stackView中的IB中设置它们。 - 添加面具 - 添加宽度和颜色的边框 - 添加阴影。

正在添加边框,但面具也会被切断。

代码:

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
}

知道如何在第一张照片中获得结果吗?

编辑:正在剪切边框,结果只是来自Xcode的UI调试器。遗憾。

3 个答案:

答案 0 :(得分:2)

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
}

示例输出:

enter image description here

答案 1 :(得分:1)

你忘了剪辑你的观点了。

self.clipsToBounds = true

答案 2 :(得分:1)

您需要将maskstobounds设置为视图层

 segmentView.layer.masksToBounds = true