2017-04-15 43 views
2

我以編程方式在視圖控制器上添加了uiview作爲子視圖(稱爲contentView)。我還以編程方式在該uiview上添加了一個圖像。每次我在iPad上運行應用程序時,圖像都被拉長了!如何修復圖像,使其適合iPad屏幕,但不會拉伸圖像?我知道drawInRect是拉伸形象。那麼我該如何解決這個問題?如何以編程方式使用uiview上的圖像

這是我的代碼:

UIGraphicsBeginImageContextWithOptions(self.contentView.bounds.size, self.contentView.opaque, 0.0); 

[[UIImage imageNamed:@"menu image 2.JPG"] drawInRect:self.contentView.bounds]; 

UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 

UIGraphicsEndImageContext(); 

UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 

[self.contentView addSubview:imageView]; 
+2

沒有任何理由對這種複雜的圖像assignement? '[[UIImageView alloc] initWithImage:[UIImage imageNamed:@「menu image 2.JPG」]];' - 這應該是所有需要的。爲此創建新的圖像上下文似乎是一種矯枉過正。 – Losiowaty

回答

2

更改代碼如下

UIImage *image = [UIImage imageNamed:@"menu image 2.JPG"]; 

UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 

imageView.contentMode = UIViewContentModeScaleAspectFit; 

[self.contentView addSubview:imageView]; 
2

的UIImageView有一個名爲contentMode屬性,它確定該圖像佈局如何在視圖上下文處理。 contentMode類型爲UIViewContentMode

默認值爲UIViewContentModeScaleToFill,它在不考慮寬高比的情況下拉伸圖像。我認爲這是導致問題的變化的縱橫比。

如果要縮放圖像,但保持縱橫比,你有兩個選擇:

  1. UIViewContentModeScaleAspectFit:這將顯示縮放來填充視圖圖像,但不能夾任何內容(如果縱橫比與視圖大小不匹配,則會顯示水平或垂直波段)

  2. UIViewContentModeScaleAspectFill:這將縮放圖像以完全填充視圖,沒有任何波段 - 這會導致內容被剪裁,如果圖像比例與視野比例不匹配。

要設置在Objective-C圖像視圖的contentMode,請使用以下語法:

UIImage *image = [UIImage imageNamed:@"menu image 2.JPG"]; 
UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 
imageView.contentMode = UIViewContentModeScaleAspectFill; 
... 

你不應該需要使用自定義的背景繪製該上班了(感謝Losiowaty問我這件事情)。

+1

如果OP已經通過在自定義上下文中繪製圖像來創建圖像的拉伸版本,這項工作是否會完成? – Losiowaty

+1

好點,忘了提。我會想象OP可以取代自定義上下文繪圖。我將更新我的文章以反映圖像如何實例化。 +1 – Yasir

+0

我明白。但是,兩者都行不通。「Aspect fit」顯示垂直頻段,「Aspect Fill」則像您所說的那樣剪輯內容。我認爲最好的解決方案應該是NSLayout約束 - 以編程方式完成尾隨,引導,頂部和底部佈局約束。任何想法如何以編程方式做到這一點?我是Objective-C的新手。所以我很感激幫助。 – TheProgrammer96

0

我想你的self.contentView.bounds沒有與你的菜單圖像2.JPG相同的長寬比。對於實驗,請嘗試查看菜單圖像2.JPG的分辨率。例如,如果它是300x150,則它的長寬比是(300/150 = 2:1)。將self.contentView.bounds設置爲此寬高比並繪製圖像並檢查結果。它不會伸展。

-1

請添加這一行代碼在您的項目

yourImage .contentMode = UIViewContentModeScaleAspectFit;