View Full Version : How to add stretchable image as background
May 22, 2011, 10:28 PM
I am trying to add a stretchable image as background in UIView with the following code. However, the image is shown one after another, but not stretched. Can anyone help me about it?
UIImage *theImage = [[UIImage imageNamed:@"BackgroundImage.png"] stretchableImageWithLeftCapWidth:0 topCapHeight:0];
[self setBackgroundColor:[UIColor colorWithPatternImage: theImage]];
May 23, 2011, 05:43 AM
I suggest you read the colorWithPatternImage: documentation (http://developer.apple.com/library/ios/documentation/uikit/reference/UIColor_Class/Reference/Reference.html#//apple_ref/occ/clm/UIColor/:colorWithPatternImage). In particular it states:
During drawing, the image in the pattern color is tiled as necessary to cover the given area.
So what you are seeing is the expected, correct, behaviour.
May 23, 2011, 11:16 AM
You are correct. My code is not the correct way to solve this problem. So what would you suggest to solve this problem? I can think about two ways to solve this problem:
1. Create an Image view and stretch the image
2. Use a very large image to set as background
May 23, 2011, 11:41 AM
I finally find a solution by modifying the root layer to display a stretched image as background. Any other better solutions?
UIImage *theImage=[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"BackgroundImage" ofType:@"png"]];
self.contentMode = UIViewContentModeScaleToFill;