2014-12-23 25 views
0

我有一張照片顯示的iOS應用程序中,用戶應該能夠查看和縮放圖像。根據要求,圖像應顯示在整個屏幕上(不應顯示透明部分,圖像應填滿整個屏幕),因此我自己使用AspectFill模式爲UIImageView。爲了實現縮放功能,使用UIScrollView並實施viewForZoomingInScrollView代表方法UIScrollView。圖像視圖連接到StoryBoard的滾動視圖的四個邊,並且兩個約束(imageHeight和imageWidth)連接到IBOutlet。這些約束將在ViewControllers viewDidLayoutSubviews方法中更新。UIView裏面的滾動查看縮放問題

我已添加以下代碼供您參考。

- (void)setImageViewModes { 
    self.scrollView.minimumZoomScale = CALCULATD_ZOOM_SCALE; 
    self.pageImageView.contentMode = UIViewContentModeScaleAspectFill; 
} 

pragma mark - UIScrollView Delegate 

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { 

    return MY_IMAGE_VIEW; 
} 

- (void)updateImageViewConstraints { 

    self.imageHeight.constant = CGRectGetHeight(self.scrollView.frame); 
    self.imageWidth.constant = CGRectGetWidth(self.scrollView.frame); 
    [self.view layoutIfNeeded]; 
} 

然而,當我嘗試縮小圖像,則反彈到其初始狀態,並且在圖像的外側部分被修剪(它僅顯示圖像的初始填充部分)。是否有任何解決方法可用於在縮小時查看整個圖像?

我試着通過設置UIScrollView的最小縮放比例(我的代碼中有一個方法來計算圖像的最小縮放比例)和縮放功能。然而,當我們縮小時,UIIMage總是移動到滾動視圖的左上角(附上屏幕截圖供您參考)。 enter image description here

我通過子類化UIScrollView並在滾動視圖的'layoutSubviews'方法中調整圖像視圖框架,找到了此問題的解決方案Center content of UIScrollView when smaller(第三個答案)。這可以在縮小時正常工作。但是,當我們縮放並滾動圖像以查看邊緣/側面部分時,滾動視圖會將圖像視圖重新調整到中心位置,並且我無法在放大狀態下看到圖像的側面部分。有關此問題的任何解決方法?

+0

你嘗試CGAffineTransformMake財產? – Vignesh

回答

1

使用此

-(void)scrollViewDidZoom:(UIScrollView *)scrollView1{ 
[self centerScrollViewContent]; 

}

- (void)centerScrollViewContent { 
CGSize boundsSize = self.scrollView.bounds.size; 
CGRect contentsFrame = self.drawingView.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.drawingView.frame = contentsFrame; 

}

0

斯威夫特3版Rahul's code

func scrollViewDidZoom(_ scrollView: UIScrollView) { 
    centerContentView() 
} 

func centerContentView() { 
    let boundsSize = scrollView.bounds.size 
    var contentFrame = contentView.frame 

    if contentFrame.size.width < boundsSize.width { 
     contentFrame.origin.x = (boundsSize.width - contentFrame.size.width)/2.0 
    } else { 
     contentFrame.origin.x = 0.0 
    } 
    if contentFrame.size.height < boundsSize.height { 
     contentFrame.origin.y = (boundsSize.height - contentFrame.size.height)/2.0 
    } else { 
     contentFrame.origin.y = 0.0 
    } 

    contentView.frame = contentFrame 
}