I'm making a few custom controls for iOS. Each of these controls draws various layers in drawRect and every single one of the layers seems to be offset for some reason. They're suppose to be centered in the view. Here's an example of a pie chart control:
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
}
}
I cannot figure out why these controls are offset in the frame. Am I doing something wrong here?