Swift View 截图转换为 UIImage - 代码示例
{"title":"Swift View 截图转换为 UIImage - 代码示例","description":"学习如何使用 Swift 代码将任意 UIView 截图转换为 UIImage 对象,并提供保存截图到相册和在 UIImageView 上显示截图的示例。","keywords":"Swift, UIView, 截图, UIImage, 扩展方法, 代码示例, 保存截图, 显示截图, UIImageView","content":"要将 Swift View 截图变成 img,你可以使用以下代码:\n\nswift\nimport UIKit\n\nextension UIView {\n\tfunc takeScreenshot() -> UIImage? {\n\t UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)\n\t drawHierarchy(in: bounds, afterScreenUpdates: true)\n\t let screenshotImage = UIGraphicsGetImageFromCurrentImageContext()\n\t UIGraphicsEndImageContext()\n\t return screenshotImage\n\t}\n}\n\n// 使用示例\nif let screenshot = view.takeScreenshot() {\n\t// 将截图保存到相册\n\tUIImageWriteToSavedPhotosAlbum(screenshot, nil, nil, nil)\n\t// 将截图显示在 UIImageView 上\n\tlet imageView = UIImageView(image: screenshot)\n\timageView.frame = CGRect(x: 0, y: 0, width: 200, height: 200)\n\tview.addSubview(imageView)\n}\n\n\n这段代码定义了一个takeScreenshot的扩展方法,可以将一个UIView截图并返回UIImage对象。你可以将截图保存到相册,或者将截图显示在 UIImageView 上,如上述示例所示。"}
原文地址: https://www.cveoy.top/t/topic/qAxp 著作权归作者所有。请勿转载和采集!