0

How do I create a CGImage from UIView Subclass?

Should I use renderInContext:UIGraphicsGetCurrentContext() to create a CG image from a view (subclass of UIView) that contains a drawing (core graphics via drawRect method)?

I have an view, myView, in which I am doing some drawing. I want to do some other core graphics operations with the drawing I have created - like blend modes etc with imported photos, so I need to get a CGimage from myView I assume. Not finding a CGImage property (my first guess). Poking around I found the solution below, but my subclass "does not declare the selector renderInContext", so I get an error.

UIGraphicsBeginImageContext(myView.bounds.size);
[myView renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

CGImageRef cgImage = image.CGImage;
Mr Wolf
  • 4,766
  • 15
  • 55
  • 91
  • Similar question: [Why do I get 'No -renderInContext: method found' warning?](http://stackoverflow.com/questions/4770544/why-do-i-get-no-renderincontext-method-found-warning) – Kurt Revis Jul 15 '12 at 05:14

1 Answers1

1

-renderInContext: is a method on CALayer, not UIView.

Do this instead:

[myView.layer renderInContext:UIGraphicsGetCurrentContext()];

You will also need to import the headers for CALayer:

 #import <QuartzCore/QuartzCore.h>

And link your app against the QuartzCore framework.

Kurt Revis
  • 26,850
  • 5
  • 64
  • 70