边框不包括背景

时间:2015-10-26 16:21:21

标签: swift uibutton uilabel border

我有一个UILabel正在使用与背景颜色相同的边框,它是半遮挡的,以创造一个很好的视觉效果。然而问题是边框外侧的标签背景颜色仍然有一个很小但很明显的条子。

边界没有覆盖整个标签!

遗憾的是,更改边框宽度也不会改变任何内容。

这是一张正在发生的事情的图片,放大了以便你可以看到它:

enter image description here

我的代码如下:

        iconLbl.frame = CGRectMake(theWidth/2-20, bottomView.frame.minY-20, 40, 40)
        iconLbl.font = UIFont.fontAwesomeOfSize(23)
        iconLbl.text = String.fontAwesomeIconWithName(.Info)
        iconLbl.layer.masksToBounds = true
        iconLbl.layer.cornerRadius = iconLbl.frame.size.width/2
        iconLbl.layer.borderWidth = 5
        iconLbl.layer.borderColor = topBackgroundColor.CGColor
        iconLbl.backgroundColor = UIColor.cyanColor()
        iconLbl.textColor = UIColor.whiteColor()

有什么我想念的吗? 或者我是否必须找出另一个才能达到这种效果?

谢谢!

编辑: 到目前为止我尝试过的事情清单!

  • 更改layer.borderWidth
  • 围绕clipToBounds / MasksToBounds
  • 围绕the layer.frame
  • 玩一个完整的框架

编辑2:

找不到修复程序!我通过将此方法扩展到我的UIViewController

来使用解决方法
func makeFakeBorder(inputView:UIView,width:CGFloat,color:UIColor) -> UIView {
        let fakeBorder = UIView()
        fakeBorder.frame = CGRectMake(inputView.frame.origin.x-width, inputView.frame.origin.y-width, inputView.frame.size.width+width*2, inputView.frame.size.height+width*2)
        fakeBorder.backgroundColor = color
        fakeBorder.clipsToBounds = true
        fakeBorder.layer.cornerRadius = fakeBorder.frame.size.width/2
        fakeBorder.addSubview(inputView)
        inputView.center = CGPointMake(fakeBorder.frame.size.width/2, fakeBorder.frame.size.height/2)
        return fakeBorder
    }

1 个答案:

答案 0 :(得分:1)

我相信这是在iOS中将边框绘制到图层的方式。在文档中说:

当此值大于0.0时,图层将使用当前的borderColor值绘制边框。 边框是根据此属性中指定的值从接收者的边界绘制的。它在接收者的内容和子层之上进行了合成,并包含cornerRadius属性的效果

解决此问题的一种方法是在视图的图层上应用蒙版,但是我发现即使如此,在进行快照测试时,仍然可以在视图周围看到很小的细线。因此,要进行更多修复,我将这段代码放到layoutSubviews

class MyView: UIView {

    override func layoutSubviews() {
        super.layoutSubviews()
    
        let maskInset: CGFloat = 1
        // Extends the layer's frame.
        layer.frame = layer.frame.inset(dx: -maskInset, dy: -maskInset)
        // Increase the border width
        layer.borderWidth = layer.borderWidth + maskInset
    
        layer.cornerRadius = bounds.height / 2
        layer.maskToBounds = true
    
        // Create a circle shape layer with true bounds.
        let mask = CAShapeLayer()
        mask.path = UIBezierPath(ovalIn: bounds.inset(dx: maskInset, dy: maskInset)).cgPath
    
        layer.mask = mask
     }
 }

CALayer's mask