如何绘制UIImage或直接在-drawRect中:?

我有一个UIImage ,我想在UIView上绘制。 但是,而不是创build一个UIImageView并将其添加为子视图,我想覆盖-drawRect:并直接绘制我的UIView。

例如,我的代码如下所示:

 - (void)drawRect:(CGRect)rect { CGContextRef myContext = UIGraphicsGetCurrentContext(); UIImage *img = [UIImage imageNamed:@"foo.png"]; // how to draw the directly into the view now? } 

调用[img drawInRect:rect];

顺便说一句,你不应该在drawRect方法中加载图像文件。 因为只要需要更新视图就会调用该方法。 因此,它(当然,加载程序)在运行中可能被多次调用。 (此外,OS2.x的imageNamed方法有一个bug – 没有caching图像,并泄漏它。)

因此,最好在初始化方法中加载文件,而不是在drawRect中。