How to add a background image to a UIView

In the iPhone SDK there isn't a setBackgroundImage function for setting the background image of a UIView. So we have to do some work to do this.

Anyway, the UIView Class has the backgroundColor property, so let's go on and use this property to reach our goal.

Fisrt we can set a color for the UIView

self.view.backgroundColor = [UIColor blueColor];

This will fille the UIView with blue color.

But this doesn't solve our problem. If we want to add a picture as background we have to do something else:




Imagine we want to use our background.png image we can do the following:

// First we create a new color with the image
UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed: @"background.png"]];

// then we set the backgroundColor property to the color created above
self.view.backgroundColor = background;
[background release];


That's already a great result, but we want more, now we want to apply some trasparencies. To do this job we have only to set properly the properties of the UIView, let's start:

self.view.opaque = NO;

self.view.alpha = 0; // the value you want, The value of this property is a floating-point number in the range 0.0 to 1.0, where 0.0 represents totally transparent and 1.0 represents totally opaque

Great! But….

we want more, if the size of our image is different from the size of the UIImage we will obtain an effect that isn't a very good effect. So we have to resize the image to fit the UIView. We have to write some code:

UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:@"background.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

self.view.backgroundColor = [UIColor colorWithPatternImage:image];


That's all, if you have found this article useful, please share it using the social button below.

Gg1



You may also like...

2 Responses

  1. Ilya says:

    Worked like a charm, thanks a lot !!!

  2. Vishal says:

    ya sure through this it set backkground Image in View
    but not In Proper format. i Want to Image in Centre of View
    any one help me!

Leave a Reply

Your email address will not be published. Required fields are marked *