Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get context from UIImageView

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?

like image 753
Undolog Avatar asked Feb 06 '26 06:02

Undolog


2 Answers

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.

like image 168
Felix Lamouroux Avatar answered Feb 08 '26 00:02

Felix Lamouroux


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

 UIGraphicsBeginImageContext(self.frame.size); 
 CGContextRef context = UIGraphicsGetCurrentContext();
like image 28
Janusz Chudzynski Avatar answered Feb 08 '26 02:02

Janusz Chudzynski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!