如何绘制UIImage或直接在-drawRect:中绘制?
我有一个 UIImage
,我想在 UIView
上绘制它。但我不想创建 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?
}
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?
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
调用
[img drawInRect:rect];
。Call
[img drawInRect:rect];
.顺便说一句,您不应该在 drawRect 方法中加载图像文件。因为每当视图需要更新时就会调用该方法。因此,它(当然是加载程序)在运行过程中可能会被调用很多次。
(此外,OS2.x的imageNamed方法有一个bug——没有缓存图像而泄露了图像。)
因此,你最好在初始化方法中加载文件,而不是在drawRect中。
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.