Zoom de UIImageView y UIScrollView


¿Realmente necesito un UIPinchGestureRecognizer dentro de un UIScrollView para que el pellizco funcione? En caso afirmativo, ¿cómo lo hago? Estoy tratando de implementar lo que tiene flipboard, donde básicamente hace zoom en una imagen y tiene la capacidad de desplazamiento después de hacer zoom. ¿Cómo hago eso?

ACTUALIZACIÓN:

Aquí hay un código que tengo que no llama al delegado de vista de desplazamiento

CGRect imgFrame;
imgFrame.size.width = originalImageSize.width;
imgFrame.size.height = originalImageSize.height;
imgFrame.origin.x = imageOriginPoint.x;
imgFrame.origin.y = imageOriginPoint.y;

NSData *data = [request responseData];
UIImage * image = [UIImage imageWithData:data];
imageView = [[UIImageView alloc] initWithImage:image];
[imageView setUserInteractionEnabled:YES];
[imageView setBackgroundColor:[UIColor clearColor]];
[imageView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
[imageView setFrame:CGRectMake(0, 0, imgFrame.size.width, imgFrame.size.height)];

UIScrollView * imgScrollView = [[UIScrollView alloc] initWithFrame:imageView.frame];
imgScrollView.delegate = self;
imgScrollView.showsVerticalScrollIndicator = NO;
imgScrollView.showsHorizontalScrollIndicator = NO;
[imgScrollView setScrollEnabled:YES];
[imgScrollView setClipsToBounds:YES];
[imgScrollView addSubview:imageView];
[imgScrollView setBackgroundColor:[UIColor blueColor]];
[imgScrollView setMaximumZoomScale:1.0];
Author: pkamb, 2012-01-17

5 answers

Todo lo que necesita hacer es agregar su UIImageView (o cualquier vista que desee ampliar) dentro de su UIScrollView.

Establezca su maximumZoomScale en su UIScrollView a cualquier valor superior a 1.0 f.

Establezca usted mismo como el delegado de su UIScrollView y devuelva el UIImageView en el método viewForZooming delegate.

Eso es todo. No se necesita ningún gesto de pellizco, nada de nada. UIScrollView maneja el zoom de pellizco para usted.

 82
Author: Ignacio Inglese,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-04 10:13:02

Hice un visor de imágenes personalizado no hace mucho tiempo sin los reconocedores de pellizco. Solo UIImageView en la parte superior de UIScrollView. Allí se pasa una cadena con un enlace a la imagen y también tiene una barra de progreso. Una vez que la imagen ha terminado de cargarse, se muestra la imagen. Aquí está el código:

-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
  return self.theImageView;
}

- (CGRect)centeredFrameForScrollView:(UIScrollView *)scroll andUIView:(UIView *)rView {
  CGSize boundsSize = scroll.bounds.size;
  CGRect frameToCenter = rView.frame;
  // center horizontally
  if (frameToCenter.size.width < boundsSize.width) {
    frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
  }
  else {
    frameToCenter.origin.x = 0;
  }
  // center vertically
  if (frameToCenter.size.height < boundsSize.height) {
    frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
  }
  else {
    frameToCenter.origin.y = 0;
  }
  return frameToCenter;
}

-(void)scrollViewDidZoom:(UIScrollView *)scrollView
{
  self.theImageView.frame = [self centeredFrameForScrollView:self.theScrollView andUIView:self.theImageView];                               
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
  [self.resourceData setLength:0];
  self.filesize = [NSNumber numberWithLongLong:[response expectedContentLength]];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
  [self.resourceData appendData:data];
  NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[self.resourceData length]];
  self.progressBar.progress = [resourceLength floatValue] / [self.filesize floatValue];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
  self.theImage = [[UIImage alloc]initWithData:resourceData];
  self.theImageView.frame = CGRectMake(0, 0, self.theImage.size.width, self.theImage.size.height);
  self.theImageView.image = self.theImage;
  self.theScrollView.minimumZoomScale = self.theScrollView.frame.size.width / self.theImageView.frame.size.width;
  self.theScrollView.maximumZoomScale = 2.0;
  [self.theScrollView setZoomScale:self.theScrollView.minimumZoomScale];
  self.theScrollView.contentSize = self.theImageView.frame.size;
  self.theLabel.hidden = YES;
  self.progressBar.hidden = YES;
}

-(void)setImageInImageView
{
  NSURLRequest *req = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:self.imageLink]];
  NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:req delegate:self];
  if (conn)
  {
    self.resourceData = [NSMutableData data];
  }
  else
  {
    NSLog(@"Connection failed: IMageViewerViewController");
  }
}

-(void)loadView
{
  self.filesize = [[NSNumber alloc]init];
  self.progressBar = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleBar];
  self.progressBar.frame = CGRectMake(20, 240, 280, 40);
  [self.progressBar setProgress:0.0];
  self.theImageView = [[[UIImageView alloc]initWithFrame:[[UIScreen mainScreen]applicationFrame]]autorelease];
  self.theScrollView = [[[UIScrollView alloc]initWithFrame:[[UIScreen mainScreen]applicationFrame]]autorelease];
  self.theScrollView.delegate = self;
  [self.theScrollView addSubview:self.theImageView];
  self.view = self.theScrollView;
  self.theLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 200, 320, 40)];
  self.theLabel.font = [UIFont boldSystemFontOfSize:15.0f];
  self.theLabel.text = @"Please wait, file is being downloaded";
  self.theLabel.textAlignment = UITextAlignmentCenter;
  self.theLabel.hidden = NO;
  [self.view addSubview:self.progressBar];
  [self.view bringSubviewToFront:self.progressBar];
  [self.view addSubview:self.theLabel];
  [self.view bringSubviewToFront:self.    theLabel];
  [self performSelectorOnMainThread:@selector(setImageInImageView) withObject:nil waitUntilDone:NO];
}

Y el archivo de cabecera:

@interface ImageViewerViewController : UIViewController<UIScrollViewDelegate, NSURLConnectionDelegate, NSURLConnectionDataDelegate>

@property (nonatomic, retain) IBOutlet UIImageView *theImageView;
@property (nonatomic, retain) IBOutlet UIScrollView *theScrollView;
@property (nonatomic, retain) NSString *imageLink;
@property (nonatomic, retain) UIImage *theImage;
@property (nonatomic, retain) UILabel *theLabel;
@property (nonatomic, retain) UIProgressView *progressBar;
@property (nonatomic, retain) NSMutableData *resourceData;
@property (nonatomic, retain) NSNumber *filesize;
@end

Espero que ayude

 14
Author: Novarg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-17 08:15:42

Swift 2.0 Pellizcar-ampliar la imagen en los pasos de Scrollview (Swift 2.0 )

1. Restricciones de la vista de desplazamiento

introduzca la descripción de la imagen aquí

2. Añadir ImageView En ScrollView y establecer Restricciones

introduzca la descripción de la imagen aquí

3. Tome IBOutlets

IBOutlet UIScrollView * bgScrollView;
IBOutlet UIImageView * imageViewOutlet;

4. Método viewDidLoad

- (void)viewDidLoad
 {
    [super viewDidLoad];

    float minScale=bgScrollView.frame.size.width / imageViewOutlet.frame.size.width;
    bgScrollView.minimumZoomScale = minScale;
    bgScrollView.maximumZoomScale = 3.0;
    bgScrollView.contentSize = imageViewOutlet.frame.size;
    bgScrollView.delegate = self;
}

5. Scroll View Delegate Method

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return imageViewOutlet;
}
 14
Author: Shrikant Tanwade,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-25 13:50:23

Supongo que esta respuesta puede ser innecesaria, pero he tenido problemas similares a @adit y lo he resuelto de una manera muy simple (creo) y tal vez alguien con desafíos similares pueda usarla:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor yellowColor];

    UIImage *imageToLoad = [UIImage imageNamed:@"background_green"];

    self.myImageView = [[UIImageView alloc]initWithImage:imageToLoad];
    self.myScrollView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
    [self.myScrollView addSubview:self.myImageView];
    self.myScrollView.contentSize = self.myImageView.bounds.size;
    self.myScrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
    self.myScrollView.minimumZoomScale = 0.3f;
    self.myScrollView.maximumZoomScale = 3.0f;
    self.myScrollView.delegate = self;
    [self.view addSubview:self.myScrollView];
}

- (UIView *) viewForZoomingInScrollView:(UIScrollView *)scrollView {
    NSLog(@"viewForZoomingInScrollView");
    return self.myImageView;
} 

Mi problema era muy simple que había olvidado agregar self.myScrollView.delegate = self;, que fue la razón por la que tuve problemas. Me tomó una eternidad resolver ese simple problema, supongo que no vi el bosque para todos los árboles: -)

 9
Author: PeterK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-04 09:02:58

Cuando estaba desarrollando mi visor de Zoom PDF en un UIScrollView descubrí que al ejecutarlo en el Teléfono ya tiene implementado el zoom como parte del teléfono. Pero podrías echar un vistazo a esto, http://developer.apple.com/library/ios/#samplecode/ZoomingPDFViewer/Introduction/Intro.html es un fragmento de código de ejemplo que intenta implementar la funcionalidad para hacer zoom, esto es want got me started.

 2
Author: Popeye,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-17 08:15:08