PDA

View Full Version : How to add stretchable image as background




chen8002004
May 22, 2011, 09: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]];



robbieduncan
May 23, 2011, 04: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.

chen8002004
May 23, 2011, 10:16 AM
Hi robbieduncan,
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

chen8002004
May 23, 2011, 10: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.layer.contents=(id)[theImage CGImage];
self.layer.contentsGravity=kCAGravityTop;
[theImage release];
self.contentMode = UIViewContentModeScaleToFill;