我在UIScrollView中有一个UIImageView。我希望用户可以缩放和导航图像。
这是我的工作代码:
//img is the UIImageView
//scroller is the UIScrollView
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return img;
}
- (void)viewDidLoad {
[super viewDidLoad];
UIImage *image = [UIImage imageNamed:@"map_screen.png"];
img = [[UIImageView alloc] initWithImage:image];
scroller.delegate = self;
scroller.autoresizesSubviews = YES;
scroller.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
scroller.contentSize = img.frame.size;
scroller.scrollEnabled = YES;
scroller.directionalLockEnabled = NO;
scroller.userInteractionEnabled = YES;
CGSize ivsize = img.frame.size;
CGSize ssize = scroller.frame.size;
float scalex = ssize.width / ivsize.width;
float scaley = ssize.height / ivsize.height;
scroller.minimumZoomScale = fmin(1.0, fmax(scaley, scalex));
scroller.zoomScale = fmin(1.0, fmax(scalex, scaley));
[scroller addSubview:img];
img.userInteractionEnabled = YES;
}
一切正常,但发生了这种情况:最小缩放是屏幕的高度。 我的图像宽度大于高度,所以我希望最小缩放是宽度。
如果我写
scroller.minimumZoomScale = fmin(1.0, scalex);
有效,但当用户缩小时,图像不在屏幕的中心,而是在顶部。
我尝试过这样的事情
CGPoint scrollCenter = [scroller center];
[img setCenter:CGPointMake(scrollCenter.x, scrollCenter.y)];
或
img.center = scroller.center;
但是使用这个解决方案,图像不能完全滚动,如果我缩小,它会再次停留在屏幕的顶部,但是不能完全显示!
我可以做些什么来解决它?
答案 0 :(得分:11)
您必须使用scrollViewDidZoom委托功能在缩放过程中手动执行此操作...类似
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
// center the image as it becomes smaller than the size of the screen
CGSize boundsSize = scrollView.bounds.size;
CGRect frameToCenter = imageView.frame;
// center horizontally
if (frameToCenter.size.width < boundsSize.width)
{
frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
} else {
frameToCenter.origin.x = 0;
}
// center vertically
if (frameToCenter.size.height < boundsSize.height)
{
frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
} else {
frameToCenter.origin.y = 0;
}
imageView.frame = frameToCenter;
}
答案 1 :(得分:3)
Swift 3.0版本的巴斯蒂安的答案,更简洁一点:
func scrollViewDidZoom(_ scrollView: UIScrollView) {
// center the image as it becomes smaller than the size of the screen
let boundsSize = scrollView.bounds.size
var frameToCenter = imageView.frame
// center horizontally and vertically
let widthDiff = boundsSize.width - frameToCenter.size.width
let heightDiff = boundsSize.height - frameToCenter.size.height
frameToCenter.origin.x = (widthDiff > 0) ? widthDiff / 2 : 0;
frameToCenter.origin.y = (heightDiff > 0) ? heightDiff / 2 : 0;
imageView.frame = frameToCenter;
}