2010-02-05 8 views
5

Tengo un UIScrollView con zoom y panorámica. Quiero que la imagen se desplace hacia el centro después de un comando de usuario. Mi problema es calcular el tamaño y la ubicación de un marco que está en el centro de la imagen.¿Cómo puedo usar scrollRectToVisible para desplazarme al centro de una imagen?

¿Alguien sabe cómo calcular el marco correcto para el centro de mi imagen? El problema es que si el zoomScale es diferente, el marco cambia.

Gracias!

+0

http://www.raywenderlich.com/10518/how-to-use-uiscrollview-to-scroll-and-zoom-content –

Respuesta

12

aquí es tal vez un poco mejor código en caso de que alguien está en la necesidad ;-)

UIScrollView + CenteredScroll.h:

@interface UIScrollView (CenteredScroll) 

-(void)scrollRectToVisibleCenteredOn:(CGRect)visibleRect 
          animated:(BOOL)animated; 

@end 

UIScrollView + CenteredScroll.m:

@implementation UIScrollView (CenteredScroll) 

-(void)scrollRectToVisibleCenteredOn:(CGRect)visibleRect 
          animated:(BOOL)animated 
{ 
    CGRect centeredRect = CGRectMake(visibleRect.origin.x + visibleRect.size.width/2.0 - self.frame.size.width/2.0, 
            visibleRect.origin.y + visibleRect.size.height/2.0 - self.frame.size.height/2.0, 
            self.frame.size.width, 
            self.frame.size.height); 
    [self scrollRectToVisible:centeredRect 
        animated:animated]; 
} 

@end 
+0

Genial, trabaja para mi. –

-5

Bien, lo tengo funcionando. Aquí está el código en caso alguno está en necesidad:

CGFloat tempy = imageView.frame.size.height; 
CGFloat tempx = imageView.frame.size.width; 
CGRect zoomRect = CGRectMake((tempx/2)-160, (tempy/2)-240, myScrollView.frame.size.width, myScrollView.frame.size.height); 
[myScrollView scrollRectToVisible:zoomRect animated:YES]; 
+9

No realmente útil con números mágicos .. –

7

Basado en la respuesta de Daniel Bauke, actualicé su código para incluir zoom s cale:

@implementation UIScrollView (jsCenteredScroll) 

-(void)jsScrollRectToVisibleCenteredOn:(CGRect)visibleRect 
          animated:(BOOL)animated 
{ 

    CGPoint center = visibleRect.origin; 
    center.x += visibleRect.size.width/2; 
    center.y += visibleRect.size.height/2; 

    center.x *= self.zoomScale; 
    center.y *= self.zoomScale; 


    CGRect centeredRect = CGRectMake(center.x - self.frame.size.width/2.0, 
            center.y - self.frame.size.height/2.0, 
            self.frame.size.width, 
            self.frame.size.height); 
    [self scrollRectToVisible:centeredRect 
        animated:animated]; 
} 

@end 
1
private func centerScrollContent() { 
    let x = (imageView.image!.size.width * scrollView.zoomScale/2) - ((scrollView.bounds.width)/2) 
    let y = (imageView.image!.size.height * scrollView.zoomScale/2) - ((scrollView.bounds.height)/2) 
    scrollView.contentOffset = CGPointMake(x, y) 
} 
Cuestiones relacionadas