views:

1761

answers:

1

Hi,

Recently I've been trying to save on render time by minimizing the amount of time spent on allocation and duplication of resources as images by using an already allocated UIImageViews and UIImages.

What I try to do is maintain a map of all UIImages - each one unique, and reassign each one to to several UIImageViews, by demand from the game engine. As the game progresses I remove some UIImageViews from display, and later might reuse them with different preloaded UIImages.

The first time I create the UIImageView I do something like:

m_ImageView = [[UIImageView alloc] initWithImage : initialImg];

[m_ParentView addSubview: m_ImageView];

And the following times I simply switch the image:

[m_ImageView.image release];

[m_ImageView setImage otherSavedImg];

The problem is that after the switch, the new image size as displayed is identical to the initial image size. I bypassed the problem by recreating the UIImageView every time (which seems like a waste of time), but I am wondering both why this happens and how can I prevent it.

Thanks,

+2  A: 

The docs for UIImageView say "This method adjusts the frame of the receiver to match the size of the specified image." When calling "setImage:", your using a simple property setter. No extra recalculation is done. If you need to readjust the size of the UIImageView's frame, you'll have to do so manually.

Judging from the context you gave, this seems like it'll be something you'll be doing somewhat frequently. As such, I recommend creating a category for UIImageView:

UIImageView+Resizing.h:

@interface UIImageView (Resizing)

- (void) setImage:(UIImage *)newImage resize:(BOOL)shouldResize;

@end

UIImageView+Resizing.m:

@implementation UIImageView (Resizing)

- (void) setImage:(UIImage *)newImage resize:(BOOL)shouldResize {
  [self setImage:newImage];
  if (shouldResize == YES) {
    [self sizeToFit];
  }
}

@end

Now, whenever you need to change an image and resize the imageView, simply #import UIImageView+Resizing.h and use:

[myImageView setImage:anImage resize:YES];
Dave DeLong
Hey Dave,Thanks for the answer, after reading it I went back and read the UIImageView doc front to back and they indeed mention something like this:> Setting the image property does not change the size of a UIImageView. Call sizeToFit to adjust the size of the view to match the image.Very strange they do not do it with the UIImage set, but hey - you saved me a day.-Adi
Adi
Ha, I forgot about the sizeToFit method! Good find. However, I'd still recommend making a category to set the image and sizeToFit, so that it decomplicates *your* code.
Dave DeLong
I went back and changed the answer to use "sizeToFit". =)
Dave DeLong