8

我有一个带有缩放和平移功能的 UIScrollView。我希望图像在用户命令后滚动到中心。我的问题是计算图像中心框架的大小和位置。

有谁知道如何为我的图像中心计算正确的框架?问题是,如果 zoomScale 不同,则框架会发生变化。

谢谢!

4

4 回答 4

17

如果有人需要,这里可能会有更好的代码;-)

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
于 2011-10-06T15:41:37.617 回答
7

根据 Daniel Bauke 的回答,我更新了他的代码以包含缩放比例:

@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
于 2013-03-06T21:56:57.030 回答
2
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)
}
于 2016-01-05T09:51:34.350 回答
-5

好的,开始工作了。这是任何人需要的代码:

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];
于 2010-02-06T16:11:26.423 回答