2014-04-14 21 views
2

目前我無法在看起來同時設置2種內容模式。但我希望圖像既縮放又居中。我該如何做到這一點?Center&Aspect Fit圖像

@property (weak, nonatomic) IBOutlet UIView *windowOut; 

self.windowOut.layer.borderColor = [UIColor redColor].CGColor; 
self.windowOut.layer.borderWidth = 3.0f; 

UIImage *face = [UIImage imageNamed:@"face.png"]; 

UIImageView* imageView = [[UIImageView alloc] initWithFrame:self.windowOut.frame]; 
imageView.contentMode = UIViewContentModeScaleAspectFit; 
imageView.contentMode = UIViewContentModeCenter; 

[imageView setImage:face]; 
[self.windowOut addSubview:imageView]; 

此圖片與上面的代碼的結果: enter image description here

此圖片的結果,當 「imageView.contentMode = UIViewContentModeCenter; 」 被註釋掉: enter image description here

編輯: 此圖片是我註釋掉這兩個內容的結果: enter image description here

+0

不管'UIViewContentModeScaleAspectFit'居中嗎? –

+0

不讓它移動大約10%,因爲一些奇怪的原因 – Esqarrouth

+0

添加圖像... – Esqarrouth

回答

2

它不集中的原因是在這裏:

UIImageView* imageView = [[UIImageView alloc] initWithFrame:self.windowOut.frame]; 

[self.windowOut addSubview:imageView]; 

這一工程,只有當windowOut恰好位於(0/0)。 .frame在其超級視圖的座標系中給出框架。如果windowOut位於,例如(20/20)位於其超級視圖(self.view?)內,那麼imageView將位於(40,40)

改爲使用bounds。這是相同的,但在其自己的座標系內。

UIImageView* imageView = [[UIImageView alloc] initWithFrame:self.windowOut.bounds]; 
[self.windowOut addSubview:imageView]; 
+0

你的第三張圖片只是證明。 'UIViewContentModeScaleAspectFit'將會。 –

+0

你的代碼對於模擬器來說是完美的,但是當我在設備上測試它時,它看起來像第三個圖像,但是居中。 可能是什麼問題? – Esqarrouth

+0

當您觀察模擬器和設備之間的奇怪變化時,請a)從模擬器中刪除應用程序,b)從設備中刪除應用程序,c)清理並重建。 –

0

如果imageView設置爲與其超視圖相同的幀,並且內容模式爲UIViewContentModeScaleAspectFit,那麼它應該按照定義居中。祝你好運!

+0

添加圖片... – Esqarrouth

+0

只是好奇,你是否嘗試不設置任何內容模式,換句話說,離開默認內容模式? – user2105505

+0

是的我認爲這個問題並不是因爲它看起來像內容模式。之後我添加了框架,現在我發現原始圖像由於某種原因也出現了居中問題。我編輯了帖子 – Esqarrouth