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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With