如何通过代码(在 Swift 中)从我的屏幕截图并保存它?
我看过,我看到这个代码,但我不能使用它(我认为),因为它没有做任何事情。
var screen = UIScreen.mainScreen()
snapstVieww = screen.snapstViewAfterScreenUpdates(false)
UIGraphicsBeginImageContextWithOptions(screen.bounds.size, false, 0)
snapstVieww.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
var image:UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
provino = UIImageView(image: image)
使用 Swift 4 / iOS 10.3,您可以选择以下方式之一来解决您的问题。
1.截取视图控制器视图的屏幕截图
以下代码显示了如何拍摄屏幕截图并将其保存在设备相册中:
import UIKit
cl ViewController: UIViewController {
/* ... */
@IBAction func screenst(_ sender: UIBarButtonItem) {
//Create the UIImage
UIGraphicsBeginImageContextWithOptions(view.frame.size, true, 0)
guard let context = UIGraphicsGetCurrentContext() else { return }
view.layer.render(in: context)
guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return }
UIGraphicsEndImageContext()
//Save it to the camera roll
UIImageWriteToSavedPtosAl(image, nil, nil, nil)
}
}
请注意,此代码的结果将是.JPG 图像。另请注意,导航栏和状态栏不会出现在最终图像中。
从 iOS 10 开始,作为前面代码的替代,您可以使用下面的代码:
import UIKit
cl ViewController: UIViewController {
/* ... */
@IBAction func screenst(_ sender: UIBarButtonItem) {
//Create the UIImage
let renderer = UIGraphicsImageRenderer(size: view.frame.size)
let image = renderer.image(actions: { context in
view.layer.render(in: context.cgContext)
})
//Save it to the camera roll
UIImageWriteToSavedPtosAl(image, nil, nil, nil)
}
}
2.拍摄 iPne 窗口的屏幕截图
如果要拍摄包含导航栏(但不包括状态栏)的屏幕截图,则可以使用以下代码:
import UIKit
cl ViewController: UIViewController {
/* ... */
@IBAction func screenst(_ sender: UIBarButtonItem) {
//Create the UIImage
guard let layer = UIApplication.shared.keyWindow?.layer else { return }
UIGraphicsBeginImageContextWithOptions(layer.frame.size, true, 0)
guard let context = UIGraphicsGetCurrentContext() else { return }
layer.render(in: context)
guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return }
UIGraphicsEndImageContext()
//Save it to the camera roll
UIImageWriteToSavedPtosAl(image, nil, nil, nil)
}
}
从 iOS 10 开始,作为前面代码的替代,您可以使用下面的代码:
import UIKit
cl ViewController: UIViewController {
/* ... */
@IBAction func screenst(_ sender: UIBarButtonItem) {
//Create the UIImage
guard let layer = UIApplication.shared.keyWindow?.layer else { return }
let renderer = UIGraphicsImageRenderer(size: layer.frame.size)
let image = renderer.image(actions: { context in
layer.render(in: context.cgContext)
})
//Save it to the camera roll
UIImageWriteToSavedPtosAl(image, nil, nil, nil)
}
}
提醒
从 iOS 10 开始,为了防止您的应用程序在调用screenst(_:)
方法时崩溃,您需要将键NSPtoLibraryUsageDescription
添加到项目的 Info.plist 文件中:
<key>NSPtoLibraryUsageDescription</key>
<string>Some description to explain why access is required</string>
只是这几行代码将获得视图的 screenSt:(只是测试)
UIGraphicsBeginImageContextWithOptions(UIScreen.mainScreen().bounds.size, false, 0);
self.view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
var image:UIImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.imgView.image = image;
/ / 在 facebook 或 twitter 上分享的截图是这样的...
func shareButtonClickedToTwitter(){
UIGraphicsBeginImageContextWithOptions(CGSizeMake(320,320), false, 0)
var image:UIImage = UIGraphicsGetImageFromCurrentImageContext();
self.view?.drawViewHierarchyInRect(CGRectMake(-30, -30, self.frame.size.width, self.frame.size.height), afterScreenUpdates: true)
var screenSt = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.vc.swTWShare("I scored \(score) in Beanystalk can you do better? Available in App Store..", shareImage: screenSt)}
func shareButtonClickedToFaceboook() {
UIGraphicsBeginImageContextWithOptions(CGSizeMake(320,320), false, 0)
var image:UIImage = UIGraphicsGetImageFromCurrentImageContext();
self.view?.drawViewHierarchyInRect(CGRectMake(-30, -30, self.frame.size.width, self.frame.size.height), afterScreenUpdates: true)
var screenSt = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.vc.swFbShare("I got \(score) Points whilst playing BeanyStalk! Can you beat me?..", shareImageF: screenSt) }
/ / facebook 分享功能。
func swFbShare(messageFB: String , shareImageF: UIImage) {
println(messageFB)
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook){
var fbSheet = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
fbSheet.completionHandler = {
result in
switch result {
case SLComposeViewControllerResult.Cancelled:
break
case SLComposeViewControllerResult.Done:
break
}
}
fbSheet.addImage(shareImageF)
fbSheet.setInitialText("\(messageFB) Click here to fun https://hereIsLink/")
println(messageFB)
self.presentViewController(fbSheet, animated: false, completion: {
})
}
else {
var alert = UIAlertController(le: "Accounts", message: "Please login to a facebook account to share.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(le: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
/ / Twitter 分享功能
func swTWShare(message: String , shareImage: UIImage) {
println(message)
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter){
var twSheet = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
twSheet.completionHandler = {
result in
switch result {
case SLComposeViewControllerResult.Cancelled:
break
case SLComposeViewControllerResult.Done:
break
}
}
twSheet.setInitialText("\(message) Click here 2 fun https://hereIsLink/") //The default text in the tweet
twSheet.addImage(shareImage)
println(message)
self.presentViewController(twSheet, animated: false, completion: {
})
}
else {
var alert = UIAlertController(le: "Accounts", message: "Please login to a Twitter account to share.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(le: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
} }
要截图,Imanou Pe 答案非常好。我已经在单个扩展中处理了多个版本的 iOS 和 tvOS,并将其作为 pod (pod 'SwiftImageEffects'
) 提供。
下面的完整代码(来自https://github.com/Coeur/ImageEffects/blob//SwiftImageEffects/ImageEffects%2Bextensions.swift):
extension UIView {
/// Get a UIImage from the UIView
/// - parameter opaque:
/// A Boolean flag indicating whether the image is opaque. Specify true to ignore the alpha channel. Specify false to handle any partially transparent pixels.
/// - parameter scale:
/// The scale factor to apply to the image. If you specify a value of 0.0, the scale factor is set to the scale factor of the device’s main screen.
open func renderImage(opaque: Bool = false, scale: CGFloat = 0) -> UIImage {
if #available(iOS 10.0, tvOS 10.0, *) {
let format = UIGraphicsImageRendererFormat.default()
format.opaque = opaque
format.scale = scale
return UIGraphicsImageRenderer(size: bounds.size, format: format).image { layer.render(in: $0.cgContext) }
} else {
// Fallback on earlier versions
// The following metds will only return a 8-bit per channel context in the DeviceRGB color e.
// Any new bitmap drawing code is encouraged to use UIGraphicsImageRenderer in lieu of this API.
UIGraphicsBeginImageContextWithOptions(bounds.size, opaque, scale)
defer { UIGraphicsEndImageContext() }
layer.render(in: UIGraphicsGetCurrentContext()!)
return UIGraphicsGetImageFromCurrentImageContext()!
}
}
}
然后你可以简单地截图:
func screenst() {
if let image = UIApplication.shared.keyWindow?.renderImage() {
// saving will require a NSPtoLibraryUsageDescription in your project's Info.plist
UIImageWriteToSavedPtosAl(image, nil, nil, nil)
}
}
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(68条)