简体   繁体   English

CALayer subLayer边界舍入错误?

[英]CALayer subLayer bounds rounding error?

The image below has been constructed using CAShapeLayer . 下图是使用CAShapeLayer构造的。 The gray layer is a sublayer of the red layer. 灰色层是红色层的子层。

If you look closely at the gray layer edges you can see the red layer edges bleeding through-- it's as if the gray layer is miscalculating it's width. 如果仔细观察灰色层的边缘,您会看到红色层的边缘正在渗出-好像灰色层在错误地计算其宽度。 This should be impossible because I set the gray layer's width to be exactly the red layer's width, and the gray layer is a sublayer of the red layer. 这应该是不可能的,因为我将灰色层的宽度设置为与红色层的宽度完全相同,而灰色层是红色层的子层。 When I print their widths they are the exact same number. 当我打印宽度时,它们是完全相同的数字。

Does anyone know what is going wrong and how to fix this? 有谁知道出了什么问题以及如何解决这个问题? Code below. 下面的代码。

It seems to be some kind of rounding error because adjusting the frame width eventually fixes the issue on certain values. 这似乎是某种舍入错误,因为调整帧宽度最终会在某些值上解决此问题。 But this still doesn't make sense because the rounding error should be the same for all sublayers. 但这仍然没有意义,因为所有子层的舍入误差都应该相同。

在此处输入图片说明

class MyLayer {
     var redLayer = CAShapeLayer()
     var grayLayer = CAShapeLayer()

      init() {
         redLayer.addSublayer(graylayer)
      }

      func layoutSublayers(_ bounds: CGRect) {
          redLayer.frame = bounds
          grayLayer.frame = CGRect(x: 0, 
                                   y: 0, 
                                   width redLayer.bounds.width, 
                                   height: redLayer.bounds.height/2)
          draw()
      }

      func draw() {
        redLayer.fillColor = UIColor.red.cgColor
        redLayer.path = UIBezierPath(rect: redLayer.bounds).cgPath
        grayLayer.fillColor = UIColor.darkGray.cgColor
        grayLayer.path = UIBezierPath(rect: grayLayer.bounds).cgPath
      }

}

Try add gray layer inside layoutSublayers after sets the size. 设置大小后,尝试在layoutSublayers添加灰色层。 Like this: 像这样:

override func layoutSublayers(of layer: CALayer) {
    redLayer.addSublayer(graylayer)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM