Get context from UIImageView

iphone, uiimageview

Solution

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.

Problem

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?

Original source