2010-02-05 8 views
5

Ho un UIScrollView con zoom e panoramica. Voglio che l'immagine scorra al centro dopo un comando dell'utente. Il mio problema è nel calcolare la dimensione e la posizione di una cornice che si trova al centro dell'immagine.Come posso usare scrollRectToVisible per scorrere fino al centro di un'immagine?

Qualcuno sa come calcolare la cornice corretta per il centro dell'immagine? Il problema è che se lo zoomScale è diverso, il frame cambia.

Grazie!

+0

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

risposta

12

Ecco forse un po 'meglio di codice nel caso qualcuno ha bisogno ;-)

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

Ottimo, lavora per me. –

-5

Ok, ho funzionato. Ecco il codice in caso qualcuno è nel bisogno:

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

Non davvero disponibile con numeri di magia .. –

7

Sulla base della risposta di Daniel Bauke, ho aggiornato il suo codice per includere lo 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) 
} 
Problemi correlati