Swift 3中的CGRect以正确的原点旋转

时间:2016-09-29 21:09:32

标签: ios swift cocoa-touch cgaffinetransform cgrect

我尝试围绕其端点旋转一条线(细长矩形)。我有它工作正常,但第2步是缩短线,并让它仍然围绕端点(旋转中心)旋转。

    // Create and add a colored square
var rod = UIView()
var countsteps = 0
var Mass = 1
var Radius = 1.00
let rectWidth = screenWidth * 0.5
let rectVertical = screenHeight * 0.5
let rectLeft = screenWidth * 0.5

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    // set background color to blue
    rod.backgroundColor = UIColor(red: 145/255, green: 170/255, blue: 157/255, alpha: 1)
    //rod Line
    rod.frame = CGRect(x: rectLeft, y: rectVertical, width: 3, height: rectWidth)
    // finally, add the square to the screen
    self.view.addSubview(rod)

    //Create Timer
    _ = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(Acceleration.update), userInfo: nil, repeats: true)
}


func update() {
    UIView.animate(withDuration: 0.1, animations: {

        //Slope Line
        let rectSize = CGFloat(self.Radius) * self.rectWidth / 100
        let amountRotation = CGFloat(CGFloat(self.countsteps)/57.3)
        let originPoint = CGPoint(x: 0,y: 0)
        self.rod.layer.anchorPoint = originPoint
        self.rod.transform = CGAffineTransform(rotationAngle: amountRotation)
        self.countsteps = self.countsteps + 1
        if (self.countsteps > 359) {
            self.countsteps = 0
        }
    })
}

我尝试添加此行:

self.rod.frame.size = CGSize(width: 3.00, height: rectSize)

但是,这会使盒子在围绕不同轴的比例变化时旋转。

1 个答案:

答案 0 :(得分:0)

尝试添加此行:

self.rod.layer.position = originPoint

所以,你的更新功能如下:

    func update() {
        UIView.animate(withDuration: 0.1, animations: {

            //Slope Line
            let rectSize = CGFloat(self.Radius) * self.rectWidth / 100
            let amountRotation = CGFloat(CGFloat(self.countsteps)/57.3)
            let originPoint = CGPoint(x: 0,y: 0)
            self.rod.layer.anchorPoint = originPoint
            self.rod.layer.position = originPoint
            self.rod.transform = CGAffineTransform(rotationAngle: amountRotation)
            self.countsteps = self.countsteps + 1
            if (self.countsteps > 359) {
                self.countsteps = 0
            }
        })
    }

我认真地建议在图层和视图背景中添加一些颜色,使用一些alpha,检测系统正在做什么非常有用,比如可视调试。