//
//  UIView+ScreenshotImage.swift
//  Gengmei
//
//  Created by wangyang on 2017/3/23.
//  Copyright © 2017年 更美互动信息科技有限公司. All rights reserved.
//

import Foundation
@objc public extension UIView {
    func screenshot() -> UIImage {
        if self is UIScrollView {
            let scrollView = self as! UIScrollView

            let savedContentOffset = scrollView.contentOffset
            let savedFrame = scrollView.frame

            // 使用scale才可以创建出符合屏幕分辨率的图片
//            UIGraphicsBeginImageContext(scrollView.contentSize)
            UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, false, UIScreen.main.scale)
            scrollView.contentOffset = .zero
            frame = CGRect(x: 0, y: 0, width: scrollView.contentSize.width, height: scrollView.contentSize.height)
            layer.render(in: UIGraphicsGetCurrentContext()!)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            scrollView.contentOffset = savedContentOffset
            scrollView.frame = savedFrame

            return image!
        }

//        UIGraphicsBeginImageContext(self.bounds.size)
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.main.scale)
        layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
        
    }
}
