如何使用scrollRectToVisible滚动到图像的中心?
-
18-09-2019 - |
题
我有缩放和平移一个UIScrollView。我想要的图像滚动到用户命令后的中心。我的问题是在计算是在图像的中心的框架的大小和位置。
有谁知道如何计算正确的帧为我的形象的中心?的问题是,如果是zoomScale不同帧的变化。
谢谢!
解决方案
下面是也许有点更好的代码的情况下,任何人是需要; - )
的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
其他提示
基于丹尼尔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
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)
}
好,得到它的工作。下面的代码柜面任何人是需要:
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];
不隶属于 StackOverflow