iOS/Tip

UIView -> UIImage

까칠코더 2023. 11. 15. 21:17
반응형

UIView를 UIImage로 변환하는 방법 2가지

extension UIView {
    func snapshot() -> UIImage {
        UIGraphicsImageRenderer(bounds: bounds).image { rendererContext in
            layer.render(in: rendererContext.cgContext)
        }
    }

    func toImage() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
        defer { UIGraphicsEndImageContext() }
        drawHierarchy(in: bounds, afterScreenUpdates: true)
        return UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
    }
}
반응형