Question

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,

Was it helpful?

Solution

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];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top