How to create a UIImage from the current graphics context?

前端 未结 3 786
故里飘歌
故里飘歌 2020-12-02 23:31

I\'d like to create a UIImage object from the current graphics context. More specifically, my use case is a view that the user can draw lines on. They may draw incremental

相关标签:
3条回答
  • 2020-12-03 00:12

    Swift Version

        func createImage(from view: UIView) -> UIImage {
            UIGraphicsBeginImageContext(view.bounds.size)
            view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
            let viewImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
    
            return viewImage
        }
    
    0 讨论(0)
  • 2020-12-03 00:13

    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();

    If you need to keep image around, be sure to retain it!

    EDIT: If you want to save the output of drawRect to an image, just create a bitmap context using UIGraphicsBeginImageContext and call your drawRect function with the new context bound. It's easier to do than saving the CGContextRef you're working with within drawRect - because that context may not have bitmap information associated with it.

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

    You can also use the approach that Kelvin mentioned. If you want to create an image from a more complex view like UIWebView, his method is faster. Drawing the view's layer does not require refreshing the layer, it just requires moving image data from one buffer to another!

    0 讨论(0)
  • 2020-12-03 00:20

    You need to setup the graphics context first:

    UIGraphicsBeginImageContext(myView.bounds.size);
    [myView.layer renderInContext:UIGraphicsGetCurrentContext()];
    viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    0 讨论(0)
提交回复
热议问题