How to use UIImage to resize as background

Discussion in 'iOS Programming' started by mikezang, Feb 5, 2011.

  1. mikezang macrumors 6502a

    Joined:
    May 22, 2010
    Location:
    Tokyo, Japan
    #1
    I have a image and want to it become a border as UIView, this view will be in size 320 x 60 or 160 x 200, I hope the border will keep width, what can I do?
    I tried to use code as below, but it looks like not what I need, can you help me?

    Code:
    image = [image stretchableImageWithLeftCapWidth:10 topCapHeight:10];
    UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)]; 
    iv.image = image;
    
    [self.labelView setBackgroundColor:[UIColor colorWithPatternImage:image]];
    
    //or
    
    [self.labelView addSubview:iv];
    
     

    Attached Files:

  2. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    I don't think there is a simple, one view option. You have a few less simple options:

    1) Implement a custom view that draws the background using 3 images (left, centre and right), or 9 images if you need vertical resizing as well.

    2) Use a load of UIImageViews positioned correctly with the correct resizing masks.
     
  3. dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #3
    Try using setBackgroundImage:forState: instead, as seen in the UICatalog sample code.
     
  4. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #4
    Will that not scale the image to fit? Which will cause the border on the example image posted to be a different pixel width at different sizes (which is what the OP wants to avoid).
     
  5. dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #5
    When used in conjuction with stretchableImageWithLeftCapWidth:topCapHeight:, only the center part of the image will scale. As stated in the documentation for that method in UIImage, "During scaling or resizing of the image, areas covered by a cap are not scaled or resized."
     
  6. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #6
    Cool: basically what I was suggesting hand-coding with multiple images :D
     
  7. dejo, Feb 7, 2011
    Last edited: Feb 7, 2011

    dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #7
    Yeah, it is pretty cool.

    I do believe the OP will need to tweak the image, though, so that the middle (stretchable) portion is only 1 pixel wide and high. At least that's my understanding of ensuring a properly set right cap width. I've never tried using anything other than 1.

    EDIT:

    Oh, and I believe you'll need to use a UIButton. :)
     

Share This Page