[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.

This question is related to iphone objective-c uiview uiimageview

The answer is


simple way :

   -(void) viewDidLoad {
   self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage       imageNamed:@"background.png"]];
    [super viewDidLoad];
    }

use this

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Default"]];

You want the background color of your main view to be semi-transparent? There's nothing behind it... so nothing will really happen however:

If you want to modify the alpha of any view, use the alpha property:

UIView *someView = [[UIView alloc] init];
...
someView.alpha = 0.8f; //Sets the opacity to 80%
...

Views themselves have the alpha transparency, not just UIColor.

But since your problem is that you can't read text on top of the images... either:

  1. [DESIGN] Reconsider the design/placement of the images. Are they necessary as background images? What about the placement of the labels?
  2. [CODE] It's not exactly the best solution, but what you could do is create a UIView whose frame takes up the entire page and add some alpha transparency to it. This will create an "overlay" of sorts.
UIView *overlay = [[[UIView alloc] init] autorelease];
overlay.frame = self.view.bounds;
overlay.alpha = 0.2f;
[self.view addSubview:overlay];
... Add the rest of the views

You can set multiple background image in every view using custom method as below.

make plist for every theam with background image name and other color

#import <Foundation/Foundation.h>
@interface ThemeManager : NSObject
@property (nonatomic,strong) NSDictionary*styles;
+ (ThemeManager *)sharedManager;
-(void)selectTheme;
 @end

             #import "ThemeManager.h"

            @implementation ThemeManager
            @synthesize styles;
            + (ThemeManager *)sharedManager
            {
                static ThemeManager *sharedManager = nil;
                if (sharedManager == nil)
                {
                    sharedManager = [[ThemeManager alloc] init];
                }
                [sharedManager selectTheme];
                return sharedManager;
            }
            - (id)init
            {
                if ((self = [super init]))
                {

                }
                return self;
            }
            -(void)selectTheme{
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                NSString *themeName = [defaults objectForKey:@"AppTheme"] ?: @"DefaultTheam";

                NSString *path = [[NSBundle mainBundle] pathForResource:themeName ofType:@"plist"];
                self.styles = [NSDictionary dictionaryWithContentsOfFile:path];
            }
            @end

Can use this via

 NSDictionary *styles = [ThemeManager sharedManager].styles;
 NSString *imageName = [styles objectForKey:@"backgroundImage"];
[imgViewBackGround setImage:[UIImage imageNamed:imageName]];

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"imageName.png"]];

more info with example project


It's a very bad idea to directly display any text on an irregular and ever changing background. No matter what you do, some of the time the text will be hard to read.

The best design would be to have the labels on a constant background with the images changing behind that.

You can set the labels background color from clear to white and set the from alpha to 50.0 you get a nice translucent effect. The only problem is that the label's background is a stark rectangle.

To get a label with a background with rounded corners you can use a button with user interaction disabled but the user might mistake that for a button.

The best method would be to create image of the label background you want and then put that in an imageview and put the label with the default transparent background onto of that.

Plain UIViews do not have an image background. Instead, you should make a UIImageView your main view and then rotate the images though its image property. If you set the UIImageView's mode to "Scale to fit" it will scale any image to fit the bounds of the view.


Besides all of the other responses here, I really don't think that using backgroundColor in this way is the proper way to do things. Personally, I would create a UIImageView and insert it into your view hierarchy. You can either insert it into your top view and push it all the way to the back with sendSubviewToBack: or you can make the UIImageView the parent view.

I wouldn't worry about things like how efficient each implementation is at this point because unless you actually see an issue, it really doesn't matter. Your first priority for now should be writing code that you can understand and can easily be changed. Creating a UIColor to use as your background image isn't the clearest method of doing this.


Examples related to iphone

Detect if the device is iPhone X Xcode 8 shows error that provisioning profile doesn't include signing certificate Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone Certificate has either expired or has been revoked Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve? cordova run with ios error .. Error code 65 for command: xcodebuild with args: "Could not find Developer Disk Image" Reason: no suitable image found iPad Multitasking support requires these orientations How to insert new cell into UITableView in Swift

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to uiview

How can I mimic the bottom sheet from the Maps app? UIView touch event in controller Swift addsubview and remove it Swift UIView background color opacity How do I change UIView Size? How to add constraints programmatically using Swift Load a UIView from nib in Swift Remove all constraints affecting a UIView How do I write a custom init for a UIView subclass in Swift? How to use UIVisualEffectView to Blur Image?

Examples related to uiimageview

Programmatically change the height and width of a UIImageView Xcode Swift How to set image in circle in swift How to load GIF image in Swift? How to assign an action for UIImageView object in Swift How to set corner radius of imageView? How do you create a UIImage View Programmatically - Swift UIImageView aspect fit and center Resize UIImage and change the size of UIImageView How to view .img files? iOS - UIImageView - how to handle UIImage image orientation