简体   繁体   English

在CGContext上绘制图像而不使用initWithFrame

[英]Draw images on CGContext without initWithFrame

I currently have an UIImage object which gets initialized with initWithFrame and then I have some 2D drawings in -(void)drawRect:(CGRect)rect{} with `CGContext. 我目前有一个UIImage对象,它使用initWithFrame ,然后我在-(void)drawRect:(CGRect)rect{}使用`CGContext进行了一些2D绘图。 Very basic. 非常基本的。 All I want to know is, how can I draw through the push of eg a button or any event (not only on initialization)? 我想知道的是,我如何通过推动例如按钮或任何事件(不仅仅是初始化)来绘制?

I tried copying the code inside drawRect to a new method called redraw but this results in an obvious error: 我尝试将drawRect的代码复制到一个名为redraw的新方法,但这会导致一个明显的错误:

CGContextMoveToPoint: invalid context 0x0 CGContextMoveToPoint:无效的上下文0x0

I only want to know how to be able to draw through CGContext while the UIView has been created. 我只想知道如何在创建UIView时绘制CGContext。 Not eg how to listen for an UIButton event 不是例如如何监听UIButton事件

Thank you. 谢谢。

You can only draw inside a UIView's drawRect: method or by creating your own image context. 您只能在UIView的drawRect:方法内部绘制,或者通过创建自己的图像上下文。 You cannot draw to the screen by any means other than drawRect: or implementing drawing for a CALayer. 您无法通过drawRect:以外的任何方式绘制到屏幕drawRect:或实现CALayer的绘图。 You need to set variables on your view accordingly, then call setNeedsDisplay to have it redrawn. 您需要相应地在视图上设置变量,然后调用setNeedsDisplay重新绘制它。 For example, add a property @property(retain) UIImage *image; 例如,添加属性@property(retain) UIImage *image; to your view, set the new image on it and then call setNeedsDisplay (or even better, implement the setImage: method and call [self setNeedsDisplay]; here). 在你的视图中,在其上设置新图像,然后调用setNeedsDisplay (甚至更好,实现setImage:方法并调用[self setNeedsDisplay]; here)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM