views:

520

answers:

3

I use this to assign image:

UIImage *img = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"myImage" ofType:@"png"]];
CGRect cropRect = CGRectMake(175, 0, 175, 175);
CGImageRef imageRef = CGImageCreateWithImageInRect([img CGImage], cropRect);
imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 175, 175)];
imageView.image = [UIImage imageWithCGImage:imageRef];
[self addSubview:imageView];
CGImageRelease(imageRef);

Now, I want to change the image from myImage to myImage2, so I do that:

    UIImage *img = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"myImage2" ofType:@"png"]];
CGRect cropRect = CGRectMake(175, 0, 175, 175);
CGImageRef imageRef = CGImageCreateWithImageInRect([img CGImage], cropRect);
imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 175, 175)];
imageView.image = [UIImage imageWithCGImage:imageRef];
[self addSubview:imageView];

It works, but not the way I want, I want to change the image, not add a imageView on top of the pervious one. How can I modify my code? thx u.

+1  A: 

At the moment, you're creating a new UIImageView and adding it to the list of sub views. As you're seeing, you then end up with two image views. What you want is to just change the image displayed by the first view. Retain a handle to the UIImageView you create (probably as a member field), and when you want to change the image, just write

UIImage *img = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"myImage2" ofType:@"png"]];
imageView.image = [UIImage imageWithCGImage:imageRef];
Adam Wright
+1  A: 

I am not sure why you are bothering to crop the image; just set the contentMode property appropriately. Alternative approach:

UIImage *image = [UIImage imageNamed:@"myImage.png"];
UIImage *image2 = [UIImage imageNamed:@"myImage2.png"];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:...];
imageView.contentMode = UIViewContentModeTopLeft;
imageView.image = image;
[self.view addSubView:imageView];
...
imageView.image = image2;
Paul Lynch
can I get back the imageView from [self.view] ?
Tattat
You can always use a tag and ask self.view for viewWithTag:
Paul Lynch
+1  A: 

Alternatively, this can be done with tags.

//Set up the imageView in viewDidLoad or similar
UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 175, 175)];
[imageView setTag:123];
[self.view addSubview:imageView];
[imageView release];

Then any time you want to change the image, you just have to use:

[(UIImageView*)[self.view viewWithTag:123] setImage:[UIImage imageWithCGImage:imageRef]];

Just another option, the other answers will work just as well.

Tom Irving