2016-09-29 84 views
0

我试图在其端点周围旋转一条线(薄矩形)。我让它工作正常,但第2步是缩短线条并使它仍然围绕端点(旋转中心)旋转。在Swift 3中正确旋转的CGRect

// 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) 

但是,这使箱转动而改变围绕不同轴的比例。

回答

0

尝试加入这一行:

self.rod.layer.position = originPoint 

所以,你的更新FUNC样子:

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 
      } 
     }) 
    } 

我认真建议增加一些色彩层和意见的背景下,一些字母,它是相当有助于检测系统正在做什么,如可视化调试。