0
我只想使用一個按鈕拍攝整個視圖控制器的照片。我想我要做的是拍攝uiview的屏幕截圖並將其保存在照片庫中。我想要圖片中的按鈕。拍攝整個視圖的屏幕截圖(swift3)
import UIKit
class ViewController: UIViewController {
@IBOutlet var x: UIButton!
var screenShot: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func saveScreen() {
self.screenShot = screenshot()
print("cool")
}
func screenshot() -> UIImage {
let imageSize = UIScreen.main.bounds.size as CGSize;
UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
let context = UIGraphicsGetCurrentContext()
for obj : AnyObject in UIApplication.shared.windows {
if let window = obj as? UIWindow {
if window.responds(to: #selector(getter: UIWindow.screen)) || window.screen == UIScreen.main {
// so we must first apply the layer's geometry to the graphics context
context!.saveGState();
// Center the context around the window's anchor point
context!.translateBy(x: window.center.x, y: window.center
.y);
// Apply the window's transform about the anchor point
context!.concatenate(window.transform);
// Offset by the portion of the bounds left of and above the anchor point
context!.translateBy(x: -window.bounds.size.width * window.layer.anchorPoint.x,
y: -window.bounds.size.height * window.layer.anchorPoint.y);
// Render the layer hierarchy to the current context
window.layer.render(in: context!)
// Restore the context
context!.restoreGState();
}
}
}
let image = UIGraphicsGetImageFromCurrentImageContext();
return image!
}
@IBAction func saveUIVIEW(_ sender: Any) {
self.screenShot = screenshot()
}
}
怎樣調用這個函數?我試圖把按鈕放在按鈕中,但沒有奏效。 –
我更新了我的答案。 –
我更新了我的問題。我的代碼編譯沒有運行時錯誤,但沒有保存到照片庫。 –