views:

2035

answers:

2

I have an UIImage which I want to draw on a UIView. But instead of creating an UIImageView and adding this as an 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?
}
+4  A: 

Call [img drawInRect:rect];.

Ole Begemann
+1  A: 

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