iOS view转换成Image

敖涵容
2023-12-01

iOS view转换成Image

已经渲染出来的view,生成样式一致的Image。这种方式可以成功将包含UIVisualEffectView一起转成Image。

OC

+(UIImage *)generateImgWithView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

Swift

class func generateImg(with view: UIView?) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(view?.bounds.size ?? CGSize.zero, false, 0)
        view?.drawHierarchy(in: view?.bounds ?? CGRect.zero, afterScreenUpdates: false)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
 类似资料: