gpt4 book ai didi

ios - 圆形边框不能完美剪裁/遮蔽

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:30:17 29 4
gpt4 key购买 nike

我在 Interface Builder 中制作了一个标签,具有固定高度和固定宽度的约束:
enter image description here

我将它子类化给它一个白色的圆形边框:

class CircularLabel: UILabel {
override func awakeFromNib() {
super.awakeFromNib()
layer.cornerRadius = frame.size.height / 2
layer.borderColor = UIColor.white.cgColor
layer.borderWidth = 5
layer.masksToBounds = true
clipsToBounds = true
}
}

但是裁剪/ mask 在运行时并不好:
enter image description here

我期待完美的白色边框,没有橙色像素。

iPhone 8(模拟器和真机)、iOS 11.2、Xcode 9.2、Swift 3.2

MCVE https://github.com/Coeur/stackoverflow48658502

最佳答案

您应该使用 UIBezierPath 来圆角并使用相同的路径绘制边界线。在我的例子中,我创建了 CAShapeLayer 并进行了所有调整,并将其添加为要查看的子层。


let borderLayer = CAShapeLayer()
let shapeLayer = CAShapeLayer()

let path = UIBezierPath(roundedRect: *get your view bounds*, cornerRadius: *needed radius*).cgPath

//Set this rounding path to both layers
shapeLayer.path = path
borderLayer.path = path

//adjust border layer
borderLayer.lineWidth = *border width*
borderLayer.strokeColor = *cgColor of your border*

//apply shape layer as mask to your view, it will cut your view by the corners
*yourViewInstance*.layer.mask = shapeLayer

//Set fill color for border layer as clear, because technically it just puts colored layer over your view
borderLayer.fillColor = UIColor.clear.cgColor

//Add border layer as sublayer to your view's main layer
*your view instance*.layer.addSublayer(borderLayer)

在您的情况下,动态标签的文本可能存在问题:如果文本是例如900000 它将绘制在边框下。要解决这个问题,您可以将 UILAbel 放在另一个 View 中(其中将包含形状和边框调整)并对其进行布局。
示例:
Structure and constraints

What i got: container BG - orange, border - white, superview's BG - red

Controller的viewDidLoad方法代码:

override func viewDidLoad() {
super.viewDidLoad()

self.view.backgroundColor = UIColor.red
self.containerView.backgroundColor = UIColor.orange

self.label.backgroundColor = UIColor.clear
self.label.textAlignment = .center
self.label.adjustsFontSizeToFitWidth = true
self.label.text = "9000000"

//Create Border and shape and apply it to container view

let borderLayer = CAShapeLayer()
let shapeLayer = CAShapeLayer()

let path = UIBezierPath(roundedRect: containerView.bounds, cornerRadius: containerView.bounds.width / 2).cgPath

//Set this rounding path to both layers
shapeLayer.path = path
borderLayer.path = path

//adjust border layer
borderLayer.lineWidth = 20
borderLayer.strokeColor = UIColor.white.cgColor

//apply shape layer as mask to your view, it will cut your view by the corners
self.containerView.layer.mask = shapeLayer

//Set fill color for border layer as clear, because technically it just puts colored layer over your view
borderLayer.fillColor = UIColor.clear.cgColor

//Add border layer as sublayer to your view's main layer
self.containerView.layer.addSublayer(borderLayer)
}

关于ios - 圆形边框不能完美剪裁/遮蔽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48658502/

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