2012-12-05 35 views
19

我想創建一個框,彈出我的xcode應用程序,只顯示該大小的圖像。我有以下幾種:創建一個UIImageView,裁剪一個圖像,並在50x和200y顯示100w 100h

UIImageView *newView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"beach.jpg"]]; 

但是,這會創建完整大小的圖像,並只顯示它。我怎麼會只顯示100瓦100小時50和200下?我會用CGRect嗎?

另外,我可以讓它點擊它導致它消失嗎?

編輯#1 我不想調整圖像大小 - 寧願只拉100平方像素,並將它們放在一個框架中。

+0

您需要添加UITapGestureRecognizer上的UIImageView爲攻。 – nhahtdh

+0

編輯:然後設置邊界而不是框架。您不需要contentMode,但需要將clipsToBounds設置爲YES。 – nhahtdh

回答

67

請嘗試使用下面的代碼。下面的代碼

MyImageview.contentMode = UIViewContentModeScaleAspectFill; 
MyImageview.clipsToBounds = YES; 
+0

是的......這2個需要與框架一起設置。 – nhahtdh

+0

thx P,這是調整圖像大小 - 任何方式來獲得原始大小? – timpone

+0

你試過MyImageview.contentMode = UIViewContentModeTopLeft; –

15

您可以用剪切圖像:

CGRect cropRegion = CGRectMake(50, 200, 100, 100); 
UIImage *image = [UIImage imageNamed:@"beach.jpg"]; 
CGImageRef subImage = CGImageCreateWithImageInRect(image.CGImage, cropRegion); 
UIImage *croppedImage = [UIImage imageWithCGImage:subImage]; 
UIImageView *newView = [[UIImageView alloc] initWithImage:croppedImage]; 
+0

這很好。很高興看到一個解決方案,不需要創建全新的上下文和東西只是一點點的收穫。 – weienw

8

您也可以實現通過檢查剪輯子視圖在故事板選項的裁剪效果。

enter image description here

+0

不,它不工作@Yuchenzhong –

+0

@Mansuu ....它應該工作。如果沒有,請嘗試在代碼https://stackoverflow.com/a/13715487/1035008中執行此操作,該操作應該等同於這兩個設置。 –