0

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?

Nic Hubbard
  • 41,587
  • 63
  • 251
  • 412

2 Answers2

2

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.

Nathanial Woolls
  • 5,231
  • 24
  • 32
  • Why even subclass `UIImageView`? Just use it. @nic: `contentMode` is a property that you should respect in your `drawRect`, not one that's applied for you. `UIImageView` already obeys it. – Tommy Aug 19 '11 at 20:22
  • UIImageView does not call drawRect. And since I am doing custom drawing, I need to use UIView. – Nic Hubbard Aug 19 '11 at 20:40
  • @Nathanial, I liked the idea of just adding a UIImageView as a subview of my main view. It worked perfectly! – Nic Hubbard Aug 19 '11 at 20:56
0

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];
}
SPopenko
  • 116
  • 4