2013-10-24 188 views
0

我遇到了需要將視圖重新定位到預定義位置的問題。計算定位點的旋轉角度

所有視圖都有UIPanGestureRecognizerUIRotationGestureRecognizer,並在控制器視圖中定位/旋轉。在某個事件後,視圖應該以新的旋轉角度移動到新的位置。

一切工作正常,但只要其中一個手勢識別器是活動的,因此anchorPoint改變了重新定位/旋轉失敗。

這裏是我嘗試使用anchorPoint中的轉換的方法。

- (CGPoint)centerPointWithInVisibleAreaForPoint:(CGPoint)point 
{ 
    CGPoint anchorP = self.layer.anchorPoint; 
     anchorP.x -= 0.5; 
     anchorP.y -= 0.5; 

    CGRect rect = self.bounds; 

    CGFloat widthDelta = CGRectGetWidth(self.bounds) * anchorP.x; 
    CGFloat heightDelta = CGRectGetHeight(self.bounds) * anchorP.y; 

    CGPoint newCenter = CGPointMake(point.x + widthDelta, point.y + heightDelta); 

    return newCenter; 
} 

控制器要求校正的中心點並設置視圖的中心值。之後,使用CGAffineTransformConcat(view.transform, CGAffineTransformMakeRotation(differenceAngle))設置旋轉變換。

我認爲這個問題是由以下事實引起的:預定義的目標角度是基於圍繞中心的旋轉,當圍繞不同的anchorPoint旋轉時明顯不同,但我不知道如何補償這一點。

回答

0

我發現的唯一解決方案(它畢竟是最簡單的一種)是將anchorPoint重置爲0.5/0.5並相應地修正位置。

- (void)resetAnchorPoint 
{ 
    if (!CGPointEqualToPoint(self.layer.anchorPoint, CGPointMake(0.5, 0.5))) { 

    CGFloat width = CGRectGetWidth(self.bounds); 
    CGFloat height = CGRectGetHeight(self.bounds); 

    CGPoint newPoint = CGPointMake(width * 0.5, height * 0.5); 
    CGPoint oldPoint = CGPointMake(width * self.layer.anchorPoint.x, height * self.layer.anchorPoint.y); 

    newPoint = CGPointApplyAffineTransform(newPoint, self.transform); 
    oldPoint = CGPointApplyAffineTransform(oldPoint, self.transform); 

    CGPoint position = self.layer.position; 
    position.x += (newPoint.x - oldPoint.x); 
    position.y += (newPoint.y - oldPoint.y); 

    [CATransaction setDisableActions:YES]; 
    self.layer.position = position; 
    self.layer.anchorPoint = CGPointMake(0.5, 0.5); 
    [CATransaction setDisableActions:NO]; 
    } 
}