我在UIScrollView中使用UIImageView實現縮放圖像。滾動視圖不會佔用全屏幕大小。我將scrollview的背景設爲綠色。然後我捏了一下圖像。iOS UIScrollView縮放增加空白區域
問題是,當我滾動縮放圖像時,它在滾動視圖中沒有正確居中,並且有一些右側和底部空間。如果我嘗試滾動到頂部或左側,則滾動視圖不允許以相似的空間滾動到圖像的末尾。空間的數量似乎與我捏手指時如何移動手指有關。
下面是截圖:
這裏是我的代碼:
// On viewWillAppear:
- (void)loadMyImage
{
self.myImage.contentMode = UIViewContentModeScaleAspectFit;
self.myImage.image = self.originalImage; // an UIImage loaded from gallery
self.myImage.bounds = CGRectMake(0, 0, self.originalImage.size.width, self.originalImage.size.height);
self.scrollView.bounds = CGRectMake(0,0,320,200);
self.scrollView.frame = CGRectMake(0,0,320,200);
self.scrollView.minimumZoomScale=1.0f;
self.scrollView.maximumZoomScale=2.0f;
self.scrollView.delegate = self;
self.myImage.userInteractionEnabled = YES;
}
// Scroll view zooming events:
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{return self.myImage;}
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
CGSize boundsSize = self.scrollView.bounds.size;
CGRect contentsFrame = self.myImage.frame;
if (contentsFrame.size.width < boundsSize.width) {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width)/2.0f;
} else {
contentsFrame.origin.x = 0.0f;
}
if (contentsFrame.size.height < boundsSize.height) {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height)/2.0f;
} else {
contentsFrame.origin.y = 0.0f;
}
self.myImage.center = CGPointMake(
contentsFrame.origin.x + contentsFrame.size.width/2.0f,
contentsFrame.origin.y + contentsFrame.size.height/2.0f);
CGPoint offset = CGPointMake(
self.myImage.center.x - self.scrollView.bounds.size.width/2.0f,
self.myImage.center.y - self.scrollView.bounds.size.height/2.0f);
[UIView animateWithDuration:.25 animations:^{
[self.scrollView setContentOffset:offset];
}];
NSLog(@"Final state of frame: %g x %g (%g , %g) and center (%g , %g)",
self.myImage.frame.size.width, self.myImage.frame.size.height,
self.myImage.frame.origin.x, self.myImage.frame.origin.y,
self.myImage.center.x, self.myImage.center.y);
NSLog(@"offset: (%g , %g)",
self.scrollView.contentOffset.x, self.scrollView.contentOffset.y);
NSLog(@"Inset left %g , right %g , top %g , bottom %g",
self.scrollView.contentInset.left,
self.scrollView.contentInset.right,
self.scrollView.contentInset.top,
self.scrollView.contentInset.bottom);
NSLog(@"==================================");
}
這裏是我的輸出:
Initial state of bounds: 320 x 200
of frame: 320 x 200 (0 , 0) and center (160 , 100)
offset: (0 , 0)
==================================
Final state of frame: 640 x 400 (0 , 0) and center (320 , 200)
offset: (160 , 100)
Inset left 0 , right 0 , top 0 , bottom 0
==================================
我試着設置automaticallyAdjustsScrollViewInsets爲NO,但我的看法控制器不響應選擇器。此外,內嵌報告0-s。
任何解決方案或解決方法將是偉大的。任何想法或可能的解釋這種行爲也將不勝感激。
刪除委託方法scrollViewDidEndZooming並再次檢查。 – Apurv
刪除scrollViewDidEndZooming不能解決放大問題。同樣,如果沒有該代碼,縮小圖像時也不會居中。 –