在UIView的子层中CAShapelayer的错误位置

时间:2017-10-03 13:55:22

标签: ios swift calayer

我试图在UIView的中间绘制:O-O-O但得到:

wrong position of layers

这是一个用于计算CAShapeLayer.frame位置的函数。偶数指数是点,奇数指数是线。行数总是减去一个点数。

func frameForShape(at index: Int) -> CGRect {
    let dotWidth = dotRadius * 2
    let lineWidth = (view.bounds.width - (CGFloat(numberOfDots) * dotWidth)) / CGFloat(numberOfLines)

    if index % 2 == 0 {
        let count = CGFloat(index) / 2
        let x = (lineWidth * count) + (dotWidth * count)
        return CGRect(x: x, y: 0, width: dotWidth, height: view.bounds.height)
    } else {
        let count = Double(index) / 2
        let x = (lineWidth * CGFloat(floor(count))) + (dotWidth * CGFloat(ceil(count)))
        return CGRect(x: x, y: 0, width: lineWidth, height: view.bounds.height)
    }
}

func setFrame() {
    for (index, shape) in shapes.enumerated() {
        shape.frame = frameForShape(at: index)
    }
}

frameForShape(at :)正确返回帧位置和大小

results of frameForShape(at:)

此funcs在给定帧的中心绘制路径

func linePath(rect: CGRect) -> UIBezierPath {
    let newRect = CGRect(x: rect.minX, y: rect.midY - (lineHeight / 2), width: rect.width, height: lineHeight)
    let path = UIBezierPath(rect: newRect)
    return path
}

func dotPath(rect: CGRect) -> UIBezierPath {
    let newRect = CGRect(x: rect.midX - dotRadius, y: rect.midY - dotRadius, width: dotRadius * 2, height: dotRadius * 2)
    let path = UIBezierPath(ovalIn: newRect)
    return path
}

在这里,我将CAShapeLayers添加到黄色UIView

override func awakeFromNib() {
    super.awakeFromNib()

    for shape in shapes {
        view.layer.addSublayer(shape)
    }
}

override func layoutSubviews() {
    super.layoutSubviews()
    layoutIfNeeded()

    setFrame()
    build()
}

func build() {
    for (index, shape) in shapes.enumerated() {
        if index % 2 == 0 {
            shape.path = dotPath(rect: shape.frame).cgPath
        } else {
            shape.path = linePath(rect: shape.frame).cgPath
        }
    }
}

框架是正确的,为什么点和线放错了?

我找到了这个答案:https://stackoverflow.com/a/40194019/

  

图层位置不正确 - 框架应该等于parentView

中父图层的边界

但是如果UIBezierPath(ovalIn :)和UIBezierPath(rect :)绘制所有内部框架,如何在特定位置绘制路径?

1 个答案:

答案 0 :(得分:2)

正如答案所说,只需在调用build()时将shape.frame更改为shape.bounds。

请记住,形状图层的坐标是相对于包含视图的,因此需要使用边界。