简体   繁体   中英

iOS: UIImage scale to fill inside a UIView

I am subclassing UIView, retrieving a remote image then drawing it to the view using drawRect. This works fine, but the image is then skewed based upon what I set for my views frame.

I can add a contentMode of UIViewContentModeScaleAspectFill to my UIView but it doesn't seem to apply at all to my UIImage that I am drawing, it still squishes the UIImage because it follows the views frame size.

It seems like I should do something like the following, but that just zooms the image 100% within my frame rather than following the contentMode setting:

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

Do I need to do something specific in drawRect: to make my image follow the contentMode property?

I think the simplest solution would be to subclass UIImageView instead of UIView and use the class's contentMode property. Then you don't need to call drawRect, just load the image into the imageView.

Alternately, if you need to subclass UIView, add a UIImageView to your view, setup springs and struts, set the contentMode, and load up your image.

You could use something like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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