2013-01-01 30 views
2

A UIImage設置爲「Aspect Fit」的視圖將自動動態縮放其圖像以適應UIUmageView的當前範圍,同時保持圖像的比例。設置爲「Aspect Fit」的UIView似乎對其子視圖沒有同樣的效果。在方向變化時自動縮放UIView以按比例縮放以適合父視圖

我試圖通過代碼設置父視圖,下面的代碼,並嘗試了自動調整大小掩碼(我沒有使用自動佈局)的幾個變化。我錯過了一些明顯的東西,還是我需要編寫一些代碼來根據父視圖的當前大小爲我的子視圖計算正確的比例?

[self.view setContentMode:UIViewContentModeScaleAspectFit]; 

回答

0

我一直在玩它。這是不完整的,只是處理肖像子視圖縮放,但到目前爲止工作正常。

if (self.view.bounds.size.width < self.view.bounds.size.height) { 
    NSLog(@"view is portrait"); 
    if (_sview.frame.size.width < _sview.frame.size.height) { 
     NSLog(@"subview is portrait"); 
     [UIView animateWithDuration:0.1 
         animations:^{ 
          _sview.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.0, 1.0); 
         }]; 
    } else { 
     NSLog(@"subview is landscape"); 
    } 
} else { 
    NSLog(@"landscape"); 
    if (_sview.frame.size.width < _sview.frame.size.height) { 
     [UIView animateWithDuration:0.1 
         animations:^{ 
          _sview.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.65, 0.65); 
         }]; 
    } else { 
     NSLog(@"subview is landscape"); 
    } 

} 
1

如何:

self.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; 

或者你可以試試這個:

// horizontal 
    childView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin; 

// vertical 
    childView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin; 

// both 
    childView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin; 

如果您想進一步的參考,我覺得這是兩個漂亮的問題:

1)Autoresizing masks programmatically

2)UIView and AutoresizingMask ignored

+0

非常感謝!但是從這些嘗試中看出,這些選項似乎都不會縮放子視圖以適應父視圖的邊界,同時保持子視圖的相稱性。 – Mrwolfy

6

從文檔:

內容模式指定視圖的層的緩存的位圖是怎樣調節當視圖的邊界變化。

對於圖像來說,這是在談論圖像。對於繪製其內容的觀點,這是談論繪製的內容。它確實不是影響子視圖的佈局。

你需要看看自動尺寸掩蓋了發生在子視圖。內容模式在這裏是一個紅鯡魚。如果您無法使用自動調整遮罩實現佈局,則需要實施layoutSubviews並手動計算子視圖位置和幀。

+0

是啊謝謝,我想我將不得不手動然後。似乎不是那麼重要,但它也變得有些複雜,因爲我現在已經做了一些工作。我只是想確保我不會錯過一個方法或其他會幫助你的課程。 – Mrwolfy