UIImage from CALayer in iOS

Brett picture Brett · Aug 11, 2010 · Viewed 26.5k times · Source

In my application, I have created a CALayer (with a few sublayers - the CALayer is composed of shapes added as sublayers).

I am trying to create a UIImage that I will be able to upload to a server (I have the code for this). However, I can't figure out how to add the CALayer to a UIImage.

Is this possible?

Answer

Todd Yandell picture Todd Yandell · Aug 11, 2010

Sounds like you want to render your layer into a UIImage. In that case, the method below should do the trick. Just add this to your view or controller class, or create a category on CALayer.

Obj-C

- (UIImage *)imageFromLayer:(CALayer *)layer
{
  UIGraphicsBeginImageContextWithOptions(layer.frame.size, NO, 0);

  [layer renderInContext:UIGraphicsGetCurrentContext()];
  UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();

  UIGraphicsEndImageContext();

  return outputImage;
}

Swift

func imageFromLayer(layer:CALayer) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(layer.frame.size, layer.isOpaque, 0)
    layer.render(in: UIGraphicsGetCurrentContext()!)
    let outputImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return outputImage!
}