Get context from UIImageView

夙愿已清 提交于 2019-12-13 14:28:58

问题


Can I get the context (CGContextRef) from exists UIImageView?

Detail: I have a controller link to xib file. In IB I have added a UIImageView and reference its on:

IBOutlet UIImageView *imageView;

Now, in viewDidLoad How get the UIImageView context (CGContextRef)?

Before this, If I use:

CGContextRef context = UIGraphicsGetCurrentContext();

output:

<Error>: CGContextTranslateCTM: invalid context

suggest?


回答1:


If you want to use your own drawing methods you should apply them in the drawRect: method of the UIView. You need to subclass UIView to create your own drawing logic: In XCode use File->New File and select UIView as a template which will give you the basic framework. In Interface-Builder you can first add a new view and then set it use your class under Identity Tab in the Inspector window.

The method should then start with something like this to give you a reference to the context:

- (void)drawRect:(CGRect)fr {
    CGContextRef context = UIGraphicsGetCurrentContext();
    ... DRAWING CODE ...
}

This methods automatically gets called when the view is first displayed. If your logic depends on some variables you should call setNeedsDisplay on the UIView to let the view re-run the drawing logic.

However, this will not work on UIImageView (LINK):

Subclassing Notes

Special Considerations

The UIImageView class is optimized to draw its images to the display. UIImageView will not call drawRect: a subclass. If your subclass needs custom drawing code, it is recommended you use UIView as the base class.




回答2:


Add a call to UIGraphicsBeginImageContext(self.frame.size); before UIGraphicsGetCurrentContext(); It will work.

 UIGraphicsBeginImageContext(self.frame.size); 
 CGContextRef context = UIGraphicsGetCurrentContext();


来源:https://stackoverflow.com/questions/1745710/get-context-from-uiimageview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!