iOS 带有圆角和背景错误的 UIButton

iOS UIButton with rounded corners and background bug

我发现一个关于圆形 UIButton 的奇怪问题。

这是我创建此按钮的代码块。

let roundedButton = UIButton(type: .System)
roundedButton.frame = CGRectMake(100, 100, 100, 100)
roundedButton.backgroundColor = UIColor.blackColor()
roundedButton.layer.borderColor = UIColor.whiteColor().CGColor
roundedButton.layer.borderWidth = 3.0
roundedButton.layer.cornerRadius = roundedButton.frame.size.width/2
roundedButton.layer.masksToBounds = true
self.view.addSubview(roundedButton)

如您所见,有一个带有背景颜色、边框和圆角半径的 UIButton。它是完全圆形的。但是在输出中我得到了下一个外观:

你可以看到按钮外面那个1px的边框,就是它的backroundColor(黑色)。似乎它的内部边框(白色)不是从按钮的边缘开始的。

你知道如何解决这个问题吗?

为图像添加边框时也会发生这种情况。我找不到直接解决它的方法,而是在图像后面添加了一个白色的 UIView 以实现相同的外观。

在你的情况下,在按钮后面添加一个白色的 UIView,具有更大的宽度和高度尺寸,以获得所需的边框宽度(在你的情况下,它将比按钮高 6 [3x2],宽 6) . 然后,只需将边框半径应用到 UIView 和 UIButton,瞧瞧!

改用 CAShapeLayer,它还可以提高性能:

    let roundedButton = UIButton(type: .Custom)
    roundedButton.frame = CGRectMake(100, 100, 100, 100)
    let _border = CAShapeLayer()
    _border.path = UIBezierPath(roundedRect: roundedButton.bounds, cornerRadius:roundedButton.frame.size.width/2).CGPath
    _border.frame = roundedButton.bounds
    _border.strokeColor = UIColor.whiteColor().CGColor
    _border.fillColor = UIColor.blackColor().CGColor
    _border.lineWidth = 3.0
    roundedButton.layer.addSublayer(_border)

    self.view.addSubview(roundedButton)

切记不要用roundedButton的backgroundColor,用CAShapeLayer的fillColor就可以了

我认为这是 CALayer 的错误。

我会这样做:

let borderWidth: CGFloat = 3.0

let roundedButton = UIButton(type: .System)
roundedButton.frame = CGRectMake(100, 100, 100, 100)
roundedButton.layer.cornerRadius = roundedButton.frame.size.width / 2
roundedButton.layer.backgroundColor = UIColor.whiteColor().CGColor
roundedButton.layer.masksToBounds = true

let innerLayer = CALayer()
innerLayer.frame = CGRect(
  x: borderWidth,
  y: borderWidth,
  width: roundedButton.frame.width - borderWidth * 2,
  height: roundedButton.frame.height - borderWidth * 2
)
innerLayer.backgroundColor = UIColor.blackColor().CGColor
innerLayer.cornerRadius = innerLayer.frame.size.width / 2
roundedButton.layer.addSublayer(innerLayer)