47

I have an UIImage which I want to draw on a UIView. But instead of creating an UIImageView and adding this as a subview, I want to overwrite -drawRect: and draw my UIView directly.

For example, my code looks like:

- (void)drawRect:(CGRect)rect {
    CGContextRef myContext = UIGraphicsGetCurrentContext();

    UIImage *img = [UIImage imageNamed:@"foo.png"];

    // how to draw the directly into the view now?
}
neowinston
  • 7,584
  • 10
  • 52
  • 83

2 Answers2

86

Call [img drawInRect:rect];.

Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
  • 4
    There is also `[img drawAtPoint:point]` too, although I prefer `drawInRect:`. – Sam Soffes Mar 14 '11 at 23:42
  • try to avoid this technique if you can; drawInRect and drawAtPoint have pretty terrible performance. – TomSwift Jun 28 '12 at 16:29
  • 1
    Thanks. I found these especially useful (combined with the similar NSString UIKit drawing add-ons) for views that contain background images & text and then added to scroll view. Drawing background image and text together in drawRect: avoids Quartz from blending the layers (as it would do if you used UIImageView & UILabel subviews approach) which has significant impact on scrolling performance – cidered Jul 17 '13 at 14:51
30

BTW, you shouldn't load the image file in the drawRect method. Because the method is called whenever the view is required to update. Therefore, it (of course, loading procedure) may be called many many times during running. (Furthermore, OS2.x's imageNamed method has a bug -- not cached the image and leaked it.)

Therefore, you'd better to load the file in the initialization method, not in the drawRect.

KatokichiSoft
  • 932
  • 5
  • 8
  • Thanks for that helpful information. Unfortunately, which "initialization" method do you mean? – geforce Apr 05 '12 at 15:35
  • He probably means `+(void)initialize`, or the usual `init` method, depending on what you're doing. – Mason Jul 03 '12 at 17:59