【问题标题】:UIImageView only displays when I call initWithImageUIImageView 仅在我调用 initWithImage 时显示
【发布时间】:2012-01-19 19:18:14
【问题描述】:

由于某种原因,我只能在每次使用不同图像分配/初始化它时显示 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]; 时,ivwivh 具有有效值并显示图像。但是,如果我将实现更改为:

// 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; 设置图像的地方,ivwivh 的值都为零并且不显示图像,但对图像的后续处理仍然准确。在这两种情况下,我都使用[self doRecognizeImage:self.imageView.image]; 将图像发送到处理。我不知道这怎么可能。如果在无法显示图像时处理失败,这对我来说会更有意义。

想法?谢谢。

【问题讨论】:

    标签: iphone objective-c xcode uiimageview uiimage


    【解决方案1】:

    您的图像视图可能没有针对图像调整大小,因此您将图像加载到具有零大小框架的 UIImageView 中。尝试手动将图像视图的框架设置为其他值。大致如下:

    UIImageView* test = [[UIImageView alloc] init];
    [test setFrame:CGRectMake(0, 0, 100, 100)];
    

    【讨论】:

      【解决方案2】:

      问题在于,当您在已初始化的 UIImageView 上设置 image 属性时,帧大小不会更新以匹配新的图像大小(与 initWithImage: 不同)。

      每当您遇到此类问题时,总是值得查看docs,以防您错过了什么:

      设置图像属性不会改变 UIImageView 的大小。 调用 sizeToFit 调整视图的大小以匹配图像。

      所以,在你设置好 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];     
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-29
        • 2011-08-20
        • 2019-08-06
        • 2015-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多