0
votes

I have a custom UIView. So myView class extend UIView. In initWithFrame:(CGRect)frame method I set UIImageView for my UIView as a background image.

- (id)initWithFrame:(CGRect)frame
{
 self = [super initWithFrame:frame];
 if (self) {
        self.bgImage = [[[UIImageView alloc] initWithFrame:
            CGRectMake(0, 0, frame.size.width , frame.size.height)] autorelease];
        int stretchableCap = 20;
        UIImage *bg = [UIImage imageNamed:@"myImage.png"];
        UIImage *stretchIcon = [bg 
            stretchableImageWithLeftCapWidth:stretchableCap topCapHeight:0];
    [self.bgImage setImage:stretchIcon];
 }
return self;
}

So when I create my view everything is fine.

 MyCustomView *customView = [[MyCustomView alloc] initWithFrame:CGRectMake(10, 10, 100, 50)];

But if I want to change my view size to bigger or smaller:

 customView.frame = CGRectMake(10, 10, 50, 50)];

then I have the problem with my background image. Because it's size didn't changed. What to do ? Ho to change bg image size together with view frame ?

4

4 Answers

0
votes

Try setting the autoresizing mask of the UIImageView, it will resize according to the size changes of the super view.

0
votes

My suggestion is use update function to update your custom view when you want to change the frame:

- (id)initWithFrame:(CGRect)frame
{
     self = [super initWithFrame:frame];
     if (self) {
         [self UpdateViewWithFrame:frame];
     }
     return self;
}

- (void)UpdateViewWithFrame:(CGRect)frame
{
    self.frame = frame;//set frame
    if(!self.bgImage)
    {
         //initialize your imageview
         self.bgImage = [[[UIImageView alloc] initWithFrame:
            CGRectMake(0, 0, frame.size.width , frame.size.height)] autorelease];
    }
    int stretchableCap = 20;
    UIImage *bg = [UIImage imageNamed:@"myImage.png"];
    UIImage *stretchIcon = [bg 
         stretchableImageWithLeftCapWidth:stretchableCap topCapHeight:0];
    [self.bgImage setImage:stretchIcon];
}

When you want change frame , just call this function.Have a try man.

0
votes

Set the required Autoresizingmask property attributes for the imageview correctly as it must be adjusted along with the view frames.

0
votes

So the suggestions was right. I should add autoresizing mask. Now my initWithFrame looks like that:

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
      self.bgImage = [[[UIImageView alloc] initWithFrame:
        CGRectMake(0, 0, frame.size.width , frame.size.height)] autorelease];
    int stretchableCap = 20;
    UIImage *bg = [UIImage imageNamed:@"myImage.png"];
    UIImage *stretchIcon = [bg 
        stretchableImageWithLeftCapWidth:stretchableCap topCapHeight:0];
[self.bgImage setImage:stretchIcon];
self.bgImage.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
self.autoresizesSubviews = YES;
}
return self;
}