iOS Swift Xcode 6:带自动布局锚点的CGAffineTransformRotate

时间:2014-10-14 17:00:40

标签: ios iphone swift rotation autolayout

我正在制作一个带有可旋转饼图的应用程序。但是,我的饼图围绕(0,0)旋转,我无法找到使其围绕其中心旋转的解决方案。

一些代码:

// DRAWING CODE
    // Set constants for piePieces
    let radius: CGFloat = CGFloat(screen.width * 0.43)
    let pi: CGFloat = 3.1415926535
    let sliceRad: CGFloat = 2.0 * pi / CGFloat(categoryArray.count)
    var currentAngle: CGFloat = -0.5 * sliceRad - 0.5 * pi
    let center: CGPoint = CGPoint(x: screen.width / 2.0, y: radius)
    println("Center point: \(center)")

    //container!.layer.anchorPoint = CGPoint(x: screen.width, y: radius)

    // Draw all pie charts, add them to container (chartView)
    for category in categoryArray {

        let slice = UIView()
        slice.frame = self.frame
        let shapeLayer = CAShapeLayer()
        let scoreIndex = CGFloat(category.calculateScoreIndex())
        let sliceRadius: CGFloat = scoreIndex * radius

        // Draw the path
        var path:UIBezierPath = UIBezierPath()

        path.moveToPoint(center)
        path.addLineToPoint(CGPoint(x: center.x + sliceRadius * cos(currentAngle), y: center.y + sliceRadius * sin(currentAngle)))
        path.addArcWithCenter(center, radius: sliceRadius, startAngle: currentAngle, endAngle: currentAngle + sliceRad, clockwise: true)
        path.addLineToPoint(center)
        path.closePath()

        // For next slice, add 2*pi Rad / n categories
        currentAngle += sliceRad

        // Add path to shapeLayer
        shapeLayer.path = path.CGPath
        //shapeLayer.frame = self.frame
        shapeLayer.fillColor = SurveyColors().getColor(category.categoryIndex).CGColor
        shapeLayer.anchorPoint = center

        // Add shapeLayer to sliceView
        slice.layer.addSublayer(shapeLayer)

        // Add slice to chartView
        container!.addSubview(slice)
    }

    self.addSubview(container!)
    //container!.center = center
    container!.layer.anchorPoint = center

}

我指示NSTimer每2秒执行一次旋转(用于测试目的):

func rotate() {
    let t: CGAffineTransform = CGAffineTransformRotate(container!.transform, -0.78)
    container!.transform = t;
}

饼图围绕(0,0)旋转。出了什么问题?

enter image description here Rotating around 0,0

1 个答案:

答案 0 :(得分:2)

我相信您的问题的一个很好的解决方案是设置容器视图:

container = UIView()
container!.frame = CGRect(x: 0.0, y: 0.0, width: screen.width, height: screen.width)
container!.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
container!.backgroundColor = UIColor.clearColor()

然后将所有切片添加到此容器视图中:

let slice = UIView()
slice.frame = CGRect(x: 0.0 , y: 0.0 , width: container!.bounds.width, height: container!.bounds.height)
let shapeLayer = CAShapeLayer()
let scoreIndex = CGFloat(category.calculateScoreIndex())
let sliceRadius: CGFloat = scoreIndex * radius
/*
*/
container!.addSubview(slice)

此外,请确保不要将图表作为子视图添加到具有自动布局约束的视图中(这可能会干扰您的CGAffineTransformRotate)。