gpt4 book ai didi

ios - Swift3 圆了 UIView 的两个角

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:49:06 24 4
gpt4 key购买 nike

我知道这个问题已经被问过很多次了,他们的解决方案也可用,但对我来说没有任何用处。我正在使用 Swift3 并且我想为此目的将 UIView 的任意两侧四舍五入我找到了以下解决方案

Create a rectangle with just two rounded corners in swift?

下面是我上述解决方案的代码片段

extension UIView {

/**
Rounds the given set of corners to the specified radius

- parameter corners: Corners to round
- parameter radius: Radius to round to
*/
func round(corners: UIRectCorner, radius: CGFloat) -> Void {
layer.addSublayer(_round(corners: corners, radius: radius))
}

/**
Rounds the given set of corners to the specified radius with a border

- parameter corners: Corners to round
- parameter radius: Radius to round to
- parameter borderColor: The border color
- parameter borderWidth: The border width
*/
func round(corners: UIRectCorner, radius: CGFloat, borderColor: UIColor, borderWidth: CGFloat) {
let mask = _round(corners: corners, radius: radius)
addBorder(mask: mask, borderColor: borderColor, borderWidth: borderWidth)
}

/**
Fully rounds an autolayout view (e.g. one with no known frame) with the given diameter and border

- parameter diameter: The view's diameter
- parameter borderColor: The border color
- parameter borderWidth: The border width
*/
func fullyRound(diameter: CGFloat, borderColor: UIColor, borderWidth: CGFloat) {
layer.masksToBounds = true
layer.cornerRadius = diameter / 2
layer.borderWidth = borderWidth
layer.borderColor = borderColor.cgColor;
}

}

private extension UIView {

func _round(corners: UIRectCorner, radius: CGFloat) -> CAShapeLayer {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
return mask
}

func addBorder(mask: CAShapeLayer, borderColor: UIColor, borderWidth: CGFloat) {
let borderLayer = CAShapeLayer()
borderLayer.path = mask.path
borderLayer.fillColor = UIColor.clear.cgColor
borderLayer.strokeColor = borderColor.cgColor
borderLayer.lineWidth = borderWidth
borderLayer.frame = bounds
layer.addSublayer(borderLayer)
}

}

这是我得到的结果。我不知道我做错了什么。谁能解决这个问题?

enter image description here

最佳答案

代码在 Swift 3 中测试和工作。

使用下面的扩展来创建roundCorners

extension UIView {
func roundCorners(corners:UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
}

用法:viewDidLoad

yourViewName.roundCorners(corners: [.topRight, .bottomLeft], radius: 10)

输出:

enter image description here

关于ios - Swift3 圆了 UIView 的两个角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40548735/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com