iOS的自定义控件始终是偏移的

时间:2015-10-03 06:04:33

标签: ios swift calayer drawrect

我正在为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: { $0.floatValue + $1.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
    }
}

我无法弄清楚为什么这些控件在帧中偏移。我在这里做错了吗?

1 个答案:

答案 0 :(得分:0)

问题在于这行代码:

arcLayer.frame = self.layer.frame

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