簡體   English   中英

如何以編程方式在uiview上擬合圖像

[英]How to fit an image on a uiview programmatically

我以編程方式在視圖控制器上添加了uiview作為子視圖(稱為contentView)。 我還以編程方式在該uiview上添加了一張圖片。 每次我在iPad上運行該應用程序時,圖像都會拉伸! 如何固定圖像以使其適合iPad屏幕但不拉伸圖像? 我知道drawInRect是拉伸圖像。 那么我該如何解決呢?

這是我的代碼:

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];

更改代碼如下

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

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

imageView.contentMode = UIViewContentModeScaleAspectFit;

[self.contentView addSubview:imageView];

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向我詢問此事)。

我猜你的self.contentView.bounds菜單圖像2.JPG的縱橫比不同。 為了進行實驗,請嘗試查看菜單圖片2.JPG的分辨率。 例如,如果它是300x150,則其寬高比是(300/150 = 2:1) 將self.contentView.bounds設置為此寬高比,然后繪制圖像並檢查結果。 它不會伸展。

請在您的項目中添加此單行代碼

yourImage .contentMode = UIViewContentModeScaleAspectFit;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM