openfrog
openfrog

Reputation: 40765

How to obtain a CGImageRef from the content of an UIView?

I have an UIView where I was drawing some stuff inside -drawRect:. Now I need a CGImageRef from this graphics context or bitmap of the UIView. Is there an easy way to get that?

Upvotes: 8

Views: 3459

Answers (3)

Thompsonmachine
Thompsonmachine

Reputation: 177

Swift 5

extension UIView {
    var cgImage: CGImage? {
        guard bounds.size.width > 0 && bounds.size.height > 0 else {return nil}
        UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, contentScaleFactor)
        layer.render(in: UIGraphicsGetCurrentContext()!)
        defer {UIGraphicsEndImageContext()}
        return UIGraphicsGetImageFromCurrentImageContext()!.cgImage!
    }
}

Upvotes: 0

Drew H
Drew H

Reputation: 1312

Also make sure that you add

#import <QuartzCore/QuartzCore.h>

to your code

Upvotes: 0

Ole Begemann
Ole Begemann

Reputation: 135578

Like this (typed from memory, so it might not be 100% correct):

// Get a UIImage from the view's contents
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, view.contentScaleFactor);
CGContextRef context = UIGraphicsGetCurrentContext();
[view.layer renderInContext:context];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

// Convert UIImage to CGImage
CGImageRef cgImage = image.CGImage;

Upvotes: 11

Related Questions