Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

iphone - How to set background image of a view?

I am a beginner at Obj-C/Cocoa Touch/iPhone OS.

I wish to have a background for my app with different images everytime the the view is called.

Say I have 10 images. I 've used it like this:

//random image generation
NSString* imageName;
int aRandomNumber = arc4random() % 10;
imageName =[NSString stringWithFormat:@"g%d.jpg",aRandomNumber]; 
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:imageName]]];
NSLog(@"aRandomNumber is %d", aRandomNumber);
//random image is generated

Its working fine

  • Now, say I have text labels on my view and the text isn't displaying correctly due to image colors. How can I make it a little transparent? (I guess in Interface Builder its called alpha.)
  • Say my image isn't 320x480. How do I set it to fill the entire view?

How can I do it with UIView/UIImageView?

I found initWithHue:saturation:brightness:alpha: in the documentation but it's not working:

self.view.backgroundColor = [[UIColor alloc] initWithHue:0.0 saturation:1.0 brightness:1.0 alpha:1.0];

Please Help!


A friend suggested........

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:imageName]]];

..........he told it's more efficient because it doesn't save the image in the cache.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"imageName.png"]];

more info with example project


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...