Как можно увеличивать и уменьшать масштаб в UIImageView без UIScrollView?

Я разрабатываю приложение для iOS 4.2, iPhone, в этом приложении я загружаю изображения и сохраняю их во внутреннем хранилище (NSDocuments).

Хорошо, тогда я показываю первое изображение в UIImageView. Пользователь может перетащить палец на UIImageView (TouchesMoved), когда пользователь это сделает, я загружаю другое изображение. Если пользователь тянет вниз, я загружаю одно изображение, если перетаскиваю вверх, я загружаю другое, а также вправо и влево.

Это все сделано. Но я хочу реализовать масштабирование. До сих пор это мой код:

initialDistance -> - это расстояние между пальцами при первом прикосновении
finalDistance -> - это расстояние между пальцами при каждом их движении
x -> равно 0
y -> is 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, с помощью которого я могу перемещаться между разными изображениями, я тоже могу взглянуть.

6
задан Priyanta Singh 30 December 2015 в 12:12
поделиться