简体   繁体   English

自动调整UIImageView的大小以适合基础图像

[英]Auto resizing UIImageView to fit underlying image

I have a custom view defined in xib file, which has an UIImageView in it. 我在xib文件中定义了一个自定义视图,该文件中包含UIImageView。

The image is added programmatically. 该图像以编程方式添加。 I don't lnow the exact image size at compile time. 我不知道在编译时的确切图像大小。

Height of an imageView is constant by design, and width must be dynamic. imageView的高度在设计上是恒定的,宽度必须是动态的。

UIImageView should automatically resize to fit image after setting it, but it doesn't. 设置图像后,UIImageView应该自动调整大小以适合图像,但事实并非如此。

I've tried: 我试过了:

  • Setting "Intristic size = Placeholder" in UI Designer. 在UI Designer中设置“内部尺寸=占位符”。
  • Setting different modes like "Aspect fit" or "Aspect fill" 设置不同的模式,例如“宽高比”或“宽高比”
  • Setting constraints (see screenshot) 设置约束(请参见屏幕截图)
  • Setting size in code (see code) 在代码中设置大小(请参见代码)
  • Searching at Google and Stackoverflow and trying code examples 在Google和Stackoverflow上搜索并尝试代码示例

Nothing has helped to achieve desired result. 没有任何事情可以帮助取得预期的结果。

这是我的xib屏幕截图

There's my code: 有我的代码:

@implementation EVACustomNavBar

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self)
    {
        [[NSBundle mainBundle] loadNibNamed:@"EVACustomNavBar" owner:self options:nil];
        self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.frame.size.width, self.frame.size.height);
        [self addSubview:self.view];
    }
    return self;
}

-(void)setLogo:(UIImage *)logo
{
    NSLog(NSStringFromCGRect(self.logoView.bounds));
    NSLog(NSStringFromCGSize(logo.size));
    self.logoView.backgroundColor = [UIColor blackColor];
    self.logoView.image = logo;
    CGRect ivFrame = self.logoView.bounds;
    CGFloat aspectRatio = logo.size.width / logo.size.height;
    ivFrame.size.width = ivFrame.size.height * aspectRatio;
    self.logoView.bounds = ivFrame;
    NSLog(NSStringFromCGRect(self.logoView.bounds));
}

@end

I tried calling setLogo at viewDidLoad and viewDidAppear in my ViewController file. 我尝试在ViewController文件中的viewDidLoad和viewDidAppear处调用setLogo。

I tried both logoView.bounds and logoView.frame. 我尝试了logoView.bounds和logoView.frame。 Output is: 输出为:

logoView.bounds before setting: {{0, 0}, {0, 44}}
logo size: {82, 71}
logoView.bounds after setting{{0, 0}, {50.816898, 44}}

However I see this: 但是我看到了这个: 这是我的模拟器屏幕截图

So even setting frame of UIImageView doesn't help. 因此,即使设置UIImageView的框架也无济于事。

尝试在IB中创建宽度约束,而不是设置图像视图的边界或框架,而是将其附加到类中的IBOutlet并更新宽度约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM