旋转UIView后检查UIButton位置

时间:2011-01-13 06:42:20

标签: iphone objective-c ipad

我有一个我在UIImageView上添加的按钮。用户触摸屏幕时的方法 UIImageView将旋转,我想知道旋转完成后是否有办法获取按钮的新位置。

现在我用这种方法一直得到原来的位置:

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    NSLog(@"Xposition : %f", myButton.frame.origin.x);
    NSLog(@"Yposition : %f", myButton.frame.origin.y);

}

谢谢,

1 个答案:

答案 0 :(得分:6)

这是一个棘手的问题。参考关于frame属性的UIView文档,它声明:

  

警告:如果transform属性不是identity变换,则此属性的值是未定义的,因此应该被忽略。

所以诀窍是找到一种解决方法,这取决于你究竟需要什么。如果您只需要近似值,或者您的旋转始终是90度的倍数,CGRectApplyAffineTransform()函数可能会运行得很好。将它传递给感兴趣的UIButton的(未转换的)帧,以及按钮的当前变换,它将为您提供转换后的矩形。请注意,由于rect被定义为原点,宽度和高度,因此无法定义边长与屏幕边缘不平行的矩形。如果它不是平行的,它将返回旋转的rect的最小可能的边界矩形。

现在,如果您需要知道一个或所有转换点的确切坐标,我之前已经编写了代码来计算它们,但它更复杂一些:

- (void)computeCornersOfTransformedView:(UIView*)transformedView relativeToView:(UIView*)parentView {
    /*  Computes the coordinates of each corner of transformedView in the coordinate system 
     *  of parentView.  Each is corner represented by an independent CGPoint. Doesn't do anything
     *  with the transformed points because this is, after all, just an example.
     */

    // Cache the current transform, and restore the view to a normal position and size.
    CGAffineTransform cachedTransform = transformedView.transform;
    transformedView.transform = CGAffineTransformIdentity;

    // Note each of the (untransformed) points of interest.
    CGPoint topLeft = CGPointMake(0, 0);
    CGPoint bottomLeft = CGPointMake(0, transformedView.frame.size.height);
    CGPoint bottomRight = CGPointMake(transformedView.frame.size.width, transformedView.frame.size.height);
    CGPoint topRight = CGPointMake(transformedView.frame.size.width, 0);

    // Re-apply the transform.
    transformedView.transform = cachedTransform;

    // Use handy built-in UIView methods to convert the points.
    topLeft = [transformedView convertPoint:topLeft toView:parentView];
    bottomLeft = [transformedView convertPoint:bottomLeft toView:parentView];
    bottomRight = [transformedView convertPoint:bottomRight toView:parentView];
    topRight = [transformedView convertPoint:topRight toView:parentView];

    // Do something with the newly acquired points.
}

请原谅代码中的任何小错误,我是在浏览器中写的。不是最有帮助的IDE ......