出于某种原因,当我使用不同的图像在每次迭代中分配/初始化它时,我只能显示 UIImageView。奇怪的是我知道正在加载图像数据,因为我正在对图像进行处理并且处理正在按预期进行。简而言之,这是我尝试的两种方法:
// interface
@interface ViewController : UIViewController <UIAlertViewDelegate>
{
UIImageView *imageView;
}
@property (nonatomic, retain) UIImageView *imageView;
@end
// implementation
@implementation ViewController
@synthesize imageView;
//...
- (void) loadAndDisplayImage {
// Load testing image
UIImage *testImg;
testImg = [UIImage imageNamed:@"Test.png"];
self.imageView = [[UIImageView alloc] initWithImage:testImg];
//size of imageView rect
CGRect frame = self.imageView.frame;
int ivw = frame.size.width;
int ivh = frame.size.height;
//...
}
@end
当我使用这个方法时self.imageView = [[UIImageView alloc] initWithImage:testImg];
ivw
和ivh
具有有效值并显示图像。但是,如果我将实现更改为:
// implementation
@implementation ViewController
@synthesize imageView;
//...
- (void) viewDidLoad {
self.imageView = [[UIImageView alloc] init];
[self loadAndDisplayImage];
}
- (void) loadAndDisplayImage {
// Load testing image
UIImage *testImg;
testImg = [UIImage imageNamed:@"Test.png"];
self.imageView.image = testImg;
//size of imageView rect
CGRect frame = self.imageView.frame;
int ivw = frame.size.width;
int ivh = frame.size.height;
//...
}
@end
我使用 self.imageView.image = testImg;
设置图像的位置,值 ivw
和ivh
都为零并且没有图像显示,但对图像的后续处理仍然是准确的。在这两种情况下,我都使用 [self doRecognizeImage:self.imageView.image];
将图像发送到处理。 。我不明白这怎么可能。如果当图像无法显示时处理失败,这对我来说更有意义。
想法?谢谢。
最佳答案
问题是,当您在已初始化的 UIImageView
上设置 image
属性时,帧大小不会更新以匹配新的图像大小(与 initWithImage:
不同)。
每当您遇到此类问题时,总是值得查看 docs如果您错过了什么:
Setting the image property does not change the size of a UIImageView. Call sizeToFit to adjust the size of the view to match the image.
因此,在设置图像属性后添加对 sizeToFit
的调用:
self.imageView.image = testImg;
[self.imageView sizeToFit];
顺便说一句,当您写入属性、而不是读取属性或调用方法时,我只会使用 self.
点表示法。换句话说,您只需编写以下内容即可:
// we are not setting imageView itself here, only a property on it
imageView.image = testImg;
// this is a method call, so "self." not needed
[imageView sizeToFit];
关于iphone - UIImageView 仅在我调用 initWithImage 时显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8497311/