如何在没有UIScrollView的情况下放大和缩小UIImageView?

时间:2011-05-18 16:53:57

标签: objective-c uiimageview ios-4.2 zooming

我正在为iOS 4.2,iPhone开发应用程序,在这个应用程序中我下载图像并将其保存在内部存储(NSDocuments)中。

那么,我在UIImageView中显示第一个图像。用户可以在UIImageView(TouchesMoved)上拖动他们的手指,当用户这样做时,我加载其他图像。如果用户向下拖动,我会加载一个图像,如果向上拖动,我加载其他图像,还有左右图像。

这一切都已完成。但我想实现缩放。这是我的代码,直到现在:

initialDistance - >是第一次触摸时手指之间的距离 finalDistance - >是每次移动时手指之间的距离 x - >是0
y - >是0

    // this method calculate the distance between 2 fingers
    - (CGFloat)distanceBetweenTwoPoints:(CGPoint)fromPoint toPoint:(CGPoint)toPoint {
        float xPoint = toPoint.x - fromPoint.x;
        float yPoint = toPoint.y - fromPoint.y;

        return sqrt(xPoint * xPoint + yPoint * yPoint);
     }

        //------------------- Movimientos con los dedos ------------------------------------
        #pragma mark -
        #pragma mark UIResponder

          // First Touch
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

NSSet *allTouches = [event allTouches];

switch ([allTouches count]) {
    case 1: { //Single touch

        //Get the first touch.
        UITouch *touch1 = [[allTouches allObjects] objectAtIndex:0];

        switch ([touch1 tapCount])
        {
            case 1: //Single Tap.
            {
                // Guardo la primera localización del dedo cuando pulsa por primera vez
                //inicial = [touch1 locationInView:self.view];

            } break;
            case 2: {//Double tap. 
                //Track the initial distance between two fingers.
                //if ([[allTouches allObjects] count] >= 2) {

                // oculto/o no, la barra de arriba cuando se hace un dobleTap
                //[self switchToolBar];

            } break;
        }
    } break;
    case 2: { //Double Touch

        // calculo la distancia inicial que hay entre los dedos cuando empieza a tocar
        UITouch *touch1 = [[allTouches allObjects] objectAtIndex:0];
        UITouch *touch2 = [[allTouches allObjects] objectAtIndex:1];

        initialDistance = [self distanceBetweenTwoPoints:[touch1 locationInView:[self view]]
                                                 toPoint:[touch2 locationInView:[self view]]];
    }
    default:
        break;
}
}

// when the finger/s move to 
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{

NSSet *allTouches = [event allTouches];

switch ([allTouches count])
{
    case 1: {



    } break;
    case 2: {
        //The image is being zoomed in or out.

        UITouch *touch1 = [[allTouches allObjects] objectAtIndex:0];
        UITouch *touch2 = [[allTouches allObjects] objectAtIndex:1];

        //Calculate the distance between the two fingers.
        CGFloat finalDistance = [self distanceBetweenTwoPoints:[touch1 locationInView:[self view]]
                                                       toPoint:[touch2 locationInView:[self view]]];

        NSLog(@"Distancia Inicial :: %.f, Ditancia final :: %.f", initialDistance, finalDistance);

        float factorX = 20.0;
        float factorY = 11.0;

        // guardo la posicion de los 2 dedos
        //CGPoint dedo1 = [[[touches allObjects] objectAtIndex:0] locationInView:self.view];
        //CGPoint dedo2 = [[[touches allObjects] objectAtIndex:1] locationInView:self.view];

        // comparo para saber si el usuario esta haciendo zoom in o zoom out
        if(initialDistance < finalDistance) {
            NSLog(@"Zoom In");

            float newWidth = imagen.frame.size.width + (initialDistance - finalDistance + factorX);
            float newHeight = imagen.frame.size.height + (initialDistance - finalDistance + factorY);

            if (newWidth <= 960 && newHeight <= 640) {
                /*
                 if (dedo1.x >= dedo2.x) {
                 x = (dedo1.x + finalDistance/2); 
                 y = (dedo1.y + finalDistance/2);
                 } else {
                 x = (dedo2.x + finalDistance/2); 
                 y = (dedo2.y + finalDistance/2);
                 }
                 */

                //x = (dedo1.x);
                //y = (dedo1.y);

                imagen.frame = CGRectMake( x, y, newWidth, newHeight);
            } else {
                imagen.frame = CGRectMake( x, y, 960, 640);
            }



        }
        else {
            NSLog(@"Zoom Out");

            float newWidth = imagen.frame.size.width - (finalDistance - initialDistance + factorX);
            float newHeight = imagen.frame.size.height - (finalDistance - initialDistance + factorY);

            if (newWidth >= 480 && newHeight >= 320) { 
                /*
                 if (dedo1.x >= dedo2.x) {
                 x = (dedo1.x + finalDistance/2); 
                 y = (dedo1.y + finalDistance/2);
                 } else {
                 x = (dedo2.x + finalDistance/2); 
                 y = (dedo2.y + finalDistance/2);
                 }
                 */
                //x -= (finalDistance - initialDistance + factorX); 
                //y -= (finalDistance - initialDistance + factorX); 

                //x = (dedo1.x);
                //y = (dedo1.y);

                imagen.frame = CGRectMake( x, y, newWidth, newHeight);
            } else {
                imagen.frame = CGRectMake( 0, 0, 480, 320);
            }



        }

        initialDistance = finalDistance;

    } break;
}
}

#pragma mark -

非常感谢!!

PD:如果有一个UIScrollView方法,我可以在不同的图像之间移动,我也可以看看。

2 个答案:

答案 0 :(得分:21)

确定。您可以考虑使用UIScrollView,只是将其用于缩放功能。

假设我们有一个scrollView和一个imageView,两者都有相同的界限。添加imageView作为scrollView的子视图。

[scrollView addSubview:imageView];
scrollView.contentSize = imageView.frame.size;

要仅支持缩放而不是在scrollView viewController {}}}中进行平移,则必须采用UIScrollViewDelegate协议。

// Disabling panning/scrolling in the scrollView
scrollView.scrollEnabled = NO;

// For supporting zoom,
scrollView.minimumZoomScale = 0.5;
scrollView.maximumZoomScale = 2.0;

...

// Implement a single scroll view delegate method
- (UIView*)viewForZoomingInScrollView:(UIScrollView *)aScrollView {
    return imageView;
}

现在我们可以进行缩放。对于滑动,您可以使用适当配置的UISwipeGestureRecognizers。创建用于处理每个滑动方向的手势,并将其添加到滚动视图。

UISwipeGestureRecognizer *rightSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self selector:@selector(handleRightSwipe:)];
rightSwipe.direction = UISwipeGestureRecognizerDirectionRight;
rightSwipe.numberOfTouchesRequired = 1;
[scrollView addGesture:rightSwipe];
[rightSwipe release];

根据手势检索合适的图像,并使用imageView.image = yourImage;设置它。

答案 1 :(得分:3)

最后,在Deepak的帮助下,我使用UIImageView的transform属性进行缩放。

我在CGAffineTransform矩阵的[0,0]位置使用CGFloat来设置限制。我必须在放大时将CGFloat传递给字符串,因为当我将它与0进行比较时,这总是正确的。

最后这是我在touchesMoved中的代码,如果它对某人有用:

// comparo para saber si el usuario esta haciendo zoom in o zoom out
        if(initialDistance < finalDistance) {
            NSLog(@"Zoom Out");

            CGAffineTransform transformer = CGAffineTransformScale(imagen.transform, 1.05, 1.05);

            NSLog(@"transformer :: A: %.f, B: %.f, C: %.f, D: %.f", imagen.transform.a, imagen.transform.b, imagen.transform.c, imagen.transform.d);

            if (transformer.a < 5) {
                [UIView beginAnimations:nil context:NULL];
                [UIView setAnimationDuration: 0.2];
                imagen.transform = transformer;
                [UIView setAnimationDelegate:self];
                [UIView commitAnimations];
            }
        }
        else {
            NSLog(@"Zoom In");

            CGAffineTransform transformer = CGAffineTransformScale(imagen.transform, 0.95, 0.95);

            NSLog(@"transformer :: A: %.f, B: %.f, C: %.f, D: %.f", transformer.a, transformer.b, transformer.c, transformer.d);

            NSString *num = [NSString stringWithFormat:@"%.f", transformer.a];

            if (![num isEqualToString:@"0"]) {
                [UIView beginAnimations:nil context:NULL];
                [UIView setAnimationDuration: 0.2];
                imagen.transform = transformer;
                [UIView setAnimationDelegate:self];
                [UIView commitAnimations];
            }
        }

当然,非常感谢迪帕克。