我有一个带有缩放和平移功能的 UIScrollView。我希望图像在用户命令后滚动到中心。我的问题是计算图像中心框架的大小和位置。
有谁知道如何为我的图像中心计算正确的框架?问题是,如果 zoomScale 不同,则框架会发生变化。
谢谢!
我有一个带有缩放和平移功能的 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
根据 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
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];