swift UIView borderColor alpha值错误

e4eetjau  于 2023-09-30  发布在  Swift
关注(0)|答案(2)|浏览(103)

如果我将带有alpha的UIColor设置为UIView及其边框,则颜色不匹配。奇怪的是,边框获得了一个alpha值(它不是完全黑色的),但它并不匹配视图的背景。

示例

代码:

let color = UIColor(white: 0, alpha: 0.3)
let view = UIView(frame: .zero)
view.backgroundColor = color
view.layer.borderWidth = 5
view.layer.borderColor = color.cgColor

结果:

aelbi1ox

aelbi1ox1#

如果你想要独立的“内部”和“外部”颜色,有各种方法可以实现。
最直接的方法可能是创建一个自定义的UIView子类,并添加一个“内部”UIView作为子视图。
基本视图将包含backgroundColor = .clearlayer.borderWidthlayer.borderColor
“内部”视图将插入borderWidth

class BorderedView: UIView {
    
    override var backgroundColor: UIColor? {
        get { return innerView.backgroundColor }
        set {
            super.backgroundColor = .clear
            innerView.backgroundColor = newValue
        }
    }
    
    public var borderColor: UIColor? {
        get { return UIColor(cgColor: self.layer.borderColor ?? UIColor.clear.cgColor) }
        set {
            if let c = newValue {
                self.layer.borderColor = c.cgColor
            }
        }
    }

    public var borderWidth: CGFloat = 5.0 { didSet { updateLayout() } }
    
    private let innerView: UIView = UIView()
    
    init() {
        super.init(frame: .zero)
        commonInit()
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    func commonInit() {
        borderColor = .clear
        backgroundColor = .clear
        innerView.translatesAutoresizingMaskIntoConstraints = false
        updateLayout()
    }
    
    // we need to change the "inner" views constraints when the border width changes
    private func updateLayout() {
        
        self.layer.borderWidth = self.borderWidth
        
        innerView.removeFromSuperview()
        
        // we need to keep innerView as the First subview
        //  otherwise it will be placed on top of any other added subviews
        insertSubview(innerView, at: 0)
        
        NSLayoutConstraint.activate([
            innerView.topAnchor.constraint(equalTo: topAnchor, constant: borderWidth),
            innerView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: borderWidth),
            innerView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -borderWidth),
            innerView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -borderWidth),
        ])
        
    }
    
}
blmhpbnm

blmhpbnm2#

您的问题是,当您为UIView的背景和边框设置相同的半透明UIColor时,生成的颜色在视觉上不匹配。边框与背景的显示方式不同,即使两者使用相同的颜色值。虽然添加与背景相同颜色的边框是无用的。

相关问题