美文网首页待处理
Swift - 截取当前屏幕

Swift - 截取当前屏幕

作者: 麦志超 | 来源:发表于2020-10-30 09:17 被阅读0次
        func takeScreenshot() -> UIImage
        {
            var imageSize = CGSize.zero
            let screenSize = UIScreen.main.bounds.size
            let orientation = UIApplication.shared.statusBarOrientation
            if UIInterfaceOrientationIsPortrait(orientation)
            {
                imageSize = screenSize
            }
            else
            {
                imageSize = CGSize(width: screenSize.height, height: screenSize.width)
            }
            
            UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
            
            if let context = UIGraphicsGetCurrentContext()
            {
                for window in UIApplication.shared.windows
                {
                    context.saveGState()
                    context.translateBy(x: window.center.x, y: window.center.y)
                    context.concatenate(window.transform)
                    context.translateBy(x: -window.bounds.size.width * window.layer.anchorPoint.x, y: -window.bounds.size.height * window.layer.anchorPoint.y)
                    
                    if orientation == UIInterfaceOrientation.landscapeLeft {
                        context.rotate(by: .pi / 2)
                        context.translateBy(x: 0, y: -imageSize.width)
                    }
                    else if orientation == UIInterfaceOrientation.landscapeRight
                    {
                        context.rotate(by: -.pi / 2)
                        context.translateBy(x: -imageSize.height, y: 0)
                    }
                    else if orientation == UIInterfaceOrientation.portraitUpsideDown
                    {
                        context.rotate(by: .pi)
                        context.translateBy(x: -imageSize.width, y: -imageSize.height)
                    }
                    if window.responds(to: #selector(UIView.drawHierarchy(in:afterScreenUpdates:)))
                    {
                        window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
                    }
                    else
                    {
                        window.layer.render(in: context)
                    }
                    context.restoreGState()
                }
            }
            
            let image = UIGraphicsGetImageFromCurrentImageContext()
            
            UIGraphicsEndImageContext()
            
            if let image = image
            {
                return image
            }
            else
            {
                return UIImage()
            }
        }
    

    相关文章

      网友评论

        本文标题:Swift - 截取当前屏幕

        本文链接:https://www.haomeiwen.com/subject/ejvrvktx.html