使用CGAffineTransform转换视图坐标

时间:2012-05-21 18:51:21

标签: iphone uiscrollview cgaffinetransform

我正在使用Apple's ScrollViewSuite TapToZoom应用程序,试图在缩放图像上放置视图。这就是我想要做的事情:双击,用pi / 2旋转图像,将其缩放8倍,然后在变换图像顶部的scrollView中放置子视图。

我知道原始坐标系中视图的所需帧。所以我需要在缩放后将这些坐标转换为新系统......

来自ScrollViewSuite ......

- (void)handleDoubleTap:(UIGestureRecognizer *)gestureRecognizer {
    // double tap zooms in
    float newScale = [imageScrollView zoomScale] * 8;  // my custom zoom
    CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]];
    [imageScrollView zoomToRect:zoomRect animated:YES];
    [self rotateView:imageScrollView by:M_PI_2];      // then the twist
}

我的轮换代码......

- (void)rotateView:(UIView *)anImageView by:(CGFloat)spin {

    [UIView animateWithDuration:0.5 delay: 0.0
                        options: UIViewAnimationOptionAllowUserInteraction 
                     animations:^{
                         anImageView.transform = CGAffineTransformMakeRotation(spin);
                     }
                     completion:^(BOOL finished){}];
}

然后,在完成缩放后,将视图放在原始坐标系中的已知位置。这是我认为我需要帮助的地方......

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)_scale {

    CGFloat coX = scrollView.contentOffset.x;
    CGFloat coY = scrollView.contentOffset.y;

    // try to build the forward transformation that got us here, then invert it
    CGAffineTransform rotate = CGAffineTransformMakeRotation(M_PI_2);
    CGAffineTransform scale = CGAffineTransformMakeScale(_scale, _scale);

    // should these be negative?  some confusion here.
    CGAffineTransform translate = CGAffineTransformMakeTranslation(coX, coY);

    // what's the right order of concatenation on these?  more confusion
    CGAffineTransform aft0 = CGAffineTransformConcat(rotate, scale);
    CGAffineTransform aft1 = CGAffineTransformConcat(aft0, translate);

    // invert it
    CGAffineTransform aft = CGAffineTransformInvert(aft1);

    // this is the fixed rect in original coordinate system of the image
    // the image is at 0,0 320, 300 in the view, so this will only work
    // when the image is at the origin...  need to fix that later,too.
    CGRect rect = CGRectMake(248, 40, 90, 160);
    CGRect xformRect = CGRectApplyAffineTransform(rect, aft);

    // build a subview with this rect
    UIView *newView = [scrollView viewWithTag:888];
    if (!newView) {
        newView = [[UIView alloc] initWithFrame:xformRect];
        newView.backgroundColor = [UIColor yellowColor];
        newView.tag = 888;
        [scrollView addSubview:newView];
    } else {
        newView.frame = xformRect;
    }
    // see where it landed...
    NSLog(@"%f,%f  %f,%f", xformRect.origin.x, xformRect.origin.y, xformRect.size.width, xformRect.size.height);
}

0 个答案:

没有答案