Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the UIImageView image content by code?

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.

like image 215
Tattat Avatar asked Dec 07 '22 03:12

Tattat


1 Answers

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.

like image 127
Tom Irving Avatar answered Dec 21 '22 09:12

Tom Irving