Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here's how you can programmatically obtain a UIImage from a UIView in Swift:

// Create a function that takes a UIView as input and returns a UIImage func getImageFromView(view: UIView) -> UIImage? { UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0) view.drawHierarchy(in: view.bounds, afterScreenUpdates: true) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } // Usage example let myView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) myView.backgroundColor = .red let image = getImageFromView(view: myView) 

In this example, we first create a function getImageFromView that takes a UIView as input and returns a UIImage. Within the function, we use UIGraphicsBeginImageContextWithOptions to create a new image context with the same size as the input view. We then call view.drawHierarchy to draw the contents of the view into the image context, and use UIGraphicsGetImageFromCurrentImageContext to extract a UIImage from the context. Finally, we call UIGraphicsEndImageContext to clean up the image context and return the resulting image.

To use the function, we create a sample UIView with a red background, and then call getImageFromView passing in the view. The function returns the resulting image, which can be used as desired.