2011-11-14 22 views
3

我如何拍攝圖像並對其進行拉伸以填充屏幕UIView(320/460)如何在UIView上拉伸(縮放)圖像?

我正在加載並放置它,但正如您所看到的,需要進行一些縮放。

enter image description here

謝謝!

CGRect gameArea = CGRectMake(0, 0, 320, 460); 

UIImage *backgroundImage = [UIImage imageNamed:@"green_background.jpg"]; 
UIImageView *myImageView = [[UIImageView alloc] initWithImage:backgroundImage]; 
[myImageView setContentMode:UIViewContentModeScaleToFill]; 

UIView *topView = [[UIView alloc] initWithFrame:gameArea]; 

[topView addSubview:myImageView];  

[[self view] addSubview:topView]; 

回答

0

嘗試

UIView *view; 
view.ContentMode = UIViewContentModeScaleToFill; 
+0

似乎無法正常工作,在上面張貼代碼。請看看 – JAM

2
CGRect gameArea = CGRectMake(0, 0, 320, 460); 

UIImage *backgroundImage = [UIImage imageNamed:@"green_background.jpg"]; 
UIImageView *myImageView = [[UIImageView alloc] initWithFrame:gameArea]; 
[myImageView setImage:[backgroundImage stretchableImageWithLeftCapWidth:3 topCapHeight:3]]; 
[myImageView setUserInteractionEnabled:YES]; 
[self.view addSubview:myImageView]; 
+2

Shamsiddin是對的,我想。你忘記了設置UIImageView的大小,這就是爲什麼它沒有伸展。您需要爲UIView設置與UIImageView相同的大小。 – HotFudgeSunday

4

就像我在我的評論說,以上Shamsiddin的帖子,在需要的UIImageView大小知道在哪裏舒展開來。在這裏我使用相同大小的UIView。我添加了另一個答案,因爲UIView的代碼丟失了。所以這裏是完整的代碼。

// Area of the UIView and UIImageView 
CGRect gameArea = CGRectMake(0, 0, 320, 460); 

// Create UIImageView with Image 
UIImage *backgroundImage = [UIImage imageNamed:@"green_background.jpg"]; 
UIImageView *myImageView = [[UIImageView alloc] initWithFrame:gameArea]; 
[myImageView setImage:[backgroundImage stretchableImageWithLeftCapWidth:3 topCapHeight:3]]; 
[myImageView setUserInteractionEnabled:YES]; 

// Create UIView and insert subview 
UIView *topView = [[UIView alloc] initWithFrame:gameArea]; 
[topView addSubview:myImageView];  
[[self view] addSubview:topView]; 
+0

感謝它爲我工作! – NightFury

0

我剛剛在我自己的iOS5應用程序中做了這個,我需要動態設置背景圖像並對其進行縮放。想象一下,你在- (void)viewWillAppear:(BOOL) animated

UIImageView *imageview = [[UIImageView alloc] initWithFrame:self.view.frame]; 
[imageview setContentMode:UIViewContentModeScaleAspectFill]; 
[imageview setImage:[UIImage imageNamed:@"Background.png"]]; 
[self.view addSubview:imageview]; 
[self.view sendSubviewToBack:imageview]; 

這樣做所以我們創建視圖,設置它的縮放模式,添加背景圖片,將其設置爲在主視圖的子視圖,然後它,所以它不會推到後面佔據任何其他子視圖。

請接受這個答案。