【问题标题】:iOS: UIImage scale to fill inside a UIViewiOS:UIImage 缩放以填充 UIView
【发布时间】:2011-08-19 20:09:45
【问题描述】:

我正在继承 UIView,检索远程图像,然后使用 drawRect 将其绘制到视图中。这很好用,但是图像会根据我为视图框架设置的内容而倾斜。

我可以将 UIViewContentModeScaleAspectFill 的 contentMode 添加到我的 UIView,但它似乎根本不适用于我正在绘制的 UIImage,它仍然会挤压 UIImage,因为它遵循视图框架大小。

似乎我应该执行以下操作,但这只是将图像在我的框架内缩放 100%,而不是遵循 contentMode 设置:

[image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];

我是否需要在 drawRect: 中做一些特定的事情来使我的图像遵循 contentMode 属性?

【问题讨论】:

    标签: iphone ios uiview uiimage content-model


    【解决方案1】:

    我认为最简单的解决方案是继承 UIImageView 而不是 UIView 并使用类的 contentMode 属性。那么就不需要调用drawRect了,把图片加载到imageView中就可以了。

    或者,如果您需要继承 UIView,请将 UIImageView 添加到您的视图中,设置弹簧和支柱,设置 contentMode,然后加载您的图像。

    【讨论】:

    • 为什么还要子类UIImageView?就用它吧。 @nic:contentMode 是您应该在drawRect 中尊重的属性,而不是适用于您的属性。 UIImageView 已经服从了。
    • UIImageView 不调用 drawRect。而且由于我在做自定义绘图,所以我需要使用 UIView。
    • @Nathanial,我喜欢将 UIImageView 添加为我的主视图的子视图的想法。效果很好!
    【解决方案2】:

    你可以使用这样的东西

        // If we have a custom background image, then draw it, othwerwise call super and draw the standard nav bar
    - (void)drawRect:(CGRect)rect
    {
      if (navigationBarBackgroundImage)
        [navigationBarBackgroundImage.image drawInRect:rect];
      else
        [super drawRect:rect];
    }
    
    // Save the background image and call setNeedsDisplay to force a redraw
    -(void) setBackgroundWith:(UIImage*)backgroundImage
    {
      self.navigationBarBackgroundImage = [[[UIImageView alloc] initWithFrame:self.frame] autorelease];
      navigationBarBackgroundImage.image = backgroundImage;
      [self setNeedsDisplay];
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多