How to add stretchable image as background

Discussion in 'iPhone/iPad Programming' started by chen8002004, May 22, 2011.

  1. chen8002004, May 22, 2011
    Last edited by a moderator: May 23, 2011

    macrumors newbie

    Joined:
    May 22, 2011
    #1
    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?

    Code:
    UIImage *theImage = [[UIImage imageNamed:@"BackgroundImage.png"] stretchableImageWithLeftCapWidth:0 topCapHeight:0];
        [self setBackgroundColor:[UIColor colorWithPatternImage: theImage]];
     
  2. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    I suggest you read the colorWithPatternImage: documentation. In particular it states:

    So what you are seeing is the expected, correct, behaviour.
     
  3. thread starter macrumors newbie

    Joined:
    May 22, 2011
    #3
    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
     
  4. chen8002004, May 23, 2011
    Last edited by a moderator: May 23, 2011

    thread starter macrumors newbie

    Joined:
    May 22, 2011
    #4
    I finally find a solution by modifying the root layer to display a stretched image as background. Any other better solutions?

    Code:
    	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;
     

Share This Page