iOS 的自定义控件始终偏移

Custom Controls for iOS are always offset

我正在为 iOS 制作一些自定义控件。这些控件中的每一个都在 drawRect 中绘制不同的图层,并且由于某种原因,每个图层似乎都被偏移了。他们应该在视图中居中。下面是饼图控件的示例:

override public func drawRect(rect: CGRect) {
    super.drawRect(rect)

    _valueLayers.forEach { (sublayer : CALayer) -> () in
        sublayer.removeFromSuperlayer()
    }
    _valueLayers.removeAll(keepCapacity: false)

    let minDim = min(rect.size.width, rect.size.height)
    let maxSliceWidthScale : CGFloat = self.sliceWidthScales.count > 0 ? min(self.sliceWidthScales.sort(>).first!, CGFloat(1)) : kDefaultSliceWidthScale
    let maxSliceWidth = maxSliceWidthScale * minDim * 0.5
    let center = rect.center()
    let sum : Float = self.values.reduce(0, combine: { [=11=].floatValue + .floatValue }).floatValue
    let maxRadius = (minDim - maxSliceWidth) * 0.5

    var currentStartAngle = self.startAngle

    for var x = 0; x < self.values.count; x++ {
        let ratio = self.values[x].floatValue / sum
        let angle = CGFloat(2.0 * M_PI * Double(ratio))
        let endAngle = currentStartAngle + angle
        let sliceWidthScale = self.sliceWidthScales.count > x ? self.sliceWidthScales[x] : kDefaultSliceWidthScale
        let sliceWidth = sliceWidthScale * minDim * 0.5

        var radius = maxRadius
        switch self.sliceAlignment {
        case .Inner:
            radius -= 0.5 * (maxSliceWidth - sliceWidth)
        case .Outer:
            radius += 0.5 * (maxSliceWidth - sliceWidth)
        case .Center:
            radius = maxRadius
        }

        let arcLayer = CAShapeLayer()
        arcLayer.frame = self.layer.frame
        arcLayer.fillColor = UIColor.clearColor().CGColor
        arcLayer.path = UIBezierPath(arcCenter: center, radius: radius, startAngle: currentStartAngle, endAngle: endAngle, clockwise: self.clockwise).CGPath
        arcLayer.strokeColor = self.colors.count > x ? self.colors[x].CGColor : kDefaultSliceColor.CGColor
        arcLayer.lineWidth = sliceWidth

        _valueLayers.append(arcLayer)
        self.layer.addSublayer(arcLayer)

        currentStartAngle = endAngle
    }

    if self.showShadow {
        self.layer.masksToBounds = false
        self.layer.shadowColor = self.shadowColor.CGColor
        self.layer.shadowOpacity = self.shadowOpacity
        self.layer.shadowOffset = self.shadowOffset
        self.layer.shadowRadius = self.shadowRadius
    }
}

我不明白为什么这些控件在框架中偏移。我是不是做错了什么?

问题是这行代码:

arcLayer.frame = self.layer.frame

当图层的原点不是 (0,0) 时,子图层正在偏移。