2010-12-06 83 views
0

我有ScrollView縮放問題。有很多關於它的文章,但不知何故,我無法找到正確的解釋,教程或代碼片段。iPhone:如何僅縮放滾動視圖中的圖像

我有全屏幕scrollview和全屏imageview。在imageview內部我加載AspectFit圖像(它們可以是垂直或水平的,水平的有黑色的空間在上面和下面)。當我進行縮放時,我不僅縮放圖像,還縮放周圍區域(ImageView的其餘部分)。此外,當我旋轉模擬器,而在變焦時,圖像進入右上角而不是像開始時那樣居中。甚至幾乎沒有像素出現在屏幕上。

我真的很想只放大圖像,而不是整個imageview,或者至少讓圖像居中放大。

任何幫助歡迎..

回答

1

我解決了這個問題,它不是最好的代碼,但現在對我很好,我可能稍後再清理它。在這裏發帖,也許它會幫助某人:)

UIImage *img = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] 
            pathForResource:someImage ofType:@"jpg"]]; 
CGFloat scale; 
    if (scrollView.frame.size.width < scrollView.frame.size.height) // portrait 
     scale = scrollView.frame.size.width/img.size.width; 
    if (scrollView.frame.size.width > scrollView.frame.size.height) // landscape 
     scale = scrollView.frame.size.height/img.size.height; 

imgView.frame = CGRectMake(scrollView.frame.origin.x, scrollView.frame.origin.y, 
          img.size.width*scale, img.size.height*scale); 
imgView.center = CGPointMake(scrollView.frame.size.width/2, scrollView.frame.size.height/2); 

[imgView setImage:img]; 

[scrollView setZoomScale:scale]; 
0

從PhotoScroller示例;將此添加到layoutSubviews:

// center the image as it becomes smaller than the size of the screen 

CGSize boundsSize = self.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; 

這不會幫助縮放圖像,但至少縮放它時它會保持居中。

+0

究竟應該在哪裏放? :)我只是改變圖像與imgView.image = [UIImage imageNamed:whichNext];我並沒有真正用圖像創建任何Rect。我只是改變imageView的內容。 – yosh 2010-12-06 11:09:18