gpt4 book ai didi

iphone - 如何通过代码改变UIImageView的图片内容?

转载 作者:行者123 更新时间:2023-12-03 19:04:00 24 4
gpt4 key购买 nike

我用它来分配图像:

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);

现在,我想将图像从 myImage 更改为 myImage2,所以我这样做:

    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];

它可以工作,但不是我想要的方式,我想更改图像,而不是在上一个图像之上添加一个 imageView 。我该如何修改我的代码?谢谢你。

最佳答案

或者,这可以通过标签来完成。

//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];

然后任何时候你想改变图像,你只需要使用:

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

只是另一种选择,其他答案也同样有效。

关于iphone - 如何通过代码改变UIImageView的图片内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2758180/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com