Pergunta

Eu tenho uma UIScrollView com zoom e visão panorâmica. Eu quero a imagem para se deslocar para o centro depois de um comando do usuário. Meu problema é no cálculo do tamanho e da localização de um quadro que está no centro da imagem.

Alguém sabe como calcular a estrutura correta para o centro da minha imagem? O problema é que se o zoomScale é diferente a moldura muda.

Obrigado!

Foi útil?

Solução

Aqui está talvez um pouco melhor código no caso de alguém está em necessidade; -)

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

Outras dicas

Com base na resposta Daniel Bauke, eu atualizou seu código para incluir escala de zoom:

@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
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)
}

Ok, tenho que trabalhar. Aqui está o código meter alguém está em necessidade:

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];
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top