彼得潘的畫家友人Jorinde Jankowski (張友鷦) 有天突發奇想,
將結在樹上的Apple換成了可愛的兔子。
不過彼得潘身為蘋果迷,
當然想將兔子換回原先的蘋果。
所謂擒賊先擒王,
樹中間的兔子是我們的首要目標。
接下來彼得潘將利用UIViewContentModeScaleAspectFill,
只顯示圖片的中間區塊,
排除中間的兔子王。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
UIImage *image = [UIImage imageNamed:@"rabbit.jpg"]; | |
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 180, 300, 150)]; | |
imageView.image = image; | |
imageView.contentMode = UIViewContentModeScaleAspectFill; | |
[self.view addSubview:imageView]; |
應該可以讓原本577 * 722圖片縮放至300* 375 ( 375 = 722*300/577.0)
並且以中心為準切除上半部和下半部各112.5。
然而程式執行後,
結局卻出乎意料
沒想到,
竟然顯示完整的圖片,
圖片的大小和位置,
完全不是設定的(10, 180, 300, 150),
更可惡的,
彼得潘的眼中釘,中間的兔子王還在。
為了找出問題,
彼得潘再加上一塊半透明的長方形,
此長方形的frame設定為和彼得潘想要的圖片frame一致。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
UIImage *image = [UIImage imageNamed:@"rabbit.jpg"]; | |
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 180, 300, 150)]; | |
imageView.image = image; | |
imageView.contentMode = UIViewContentModeScaleAspectFill; | |
[self.view addSubview:imageView]; | |
UIView *blackView = [[UIView alloc] initWithFrame:imageView.frame]; | |
blackView.backgroundColor = [UIColor blackColor]; | |
blackView.alpha = 0.5; | |
[self.view addSubview:blackView]; |
如上圖所示,
彼得潘想要的圖片大小和位置,
其實是圖片的中間區塊。
實現願望其實很簡單,
只要加入以下程式碼即可
imageView.clipsToBounds = YES;
clipsToBounds的預設值是NO,
將其設為YES,
即可讓超出範圍的部分被活生生的割除!
若是從Storyboard建立的ImageView,
在將Mode設為Scale To Fill時,
顯示的預覽將是手術成功後的結果。
不過想不到彼得潘又上當了,
由於Clip Subviews沒有勾選,
實際執行時顯示的還是手術前的模樣,
兔子王還是得意地在樹上搖擺。
因此,
記得要勾選Clip Subviews,
它的效果等同於將clipsToBounds設為YES。
沒有留言:
張貼留言