2016-09-29 82 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 
      } 
     }) 
    } 

我認真建議增加一些色彩層和意見的背景下,一些字母,它是相當有助於檢測系統正在做什麼,如可視化調試。