如何在swift中截取UIView的截图?

时间:2015-07-23 08:37:29

标签: ios swift uiview screenshot

我有一个名为overView的UIView:

overView.frame = CGRectMake(self.view.frame.width/25, self.view.frame.height/25, self.view.frame.width/1.3, self.view.frame.height/1.2)

我想仅截取此视图的屏幕截图,而不是整个屏幕。并制作尺寸截图:

 (CGSizeMake(2480,3508 )

这是我的代码:

UIGraphicsBeginImageContextWithOptions(CGSizeMake(2480,3508 ), false, 0);
self.view.drawViewHierarchyInRect(CGRectMake(-self.view.frame.width/25, -self.view.frame.height/25,2480,3508), afterScreenUpdates: true)
var image:UIImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext()

屏幕截图具有所需的大小,但它需要整个视图的屏幕截图,而不仅仅是" overView"。

6 个答案:

答案 0 :(得分:29)

要绘制一个视图,只需使用:

    // Begin context
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.mainScreen().scale)

    // Draw view in that context
    drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)

    // And finally, get image
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

如果你想多次使用它,可能扩展可以完成这项工作:

// Swift4

extension UIView {

    func takeScreenshot() -> UIImage {

        // Begin context
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.main.scale)

        // Draw view in that context
        drawHierarchy(in: self.bounds, afterScreenUpdates: true)

        // And finally, get image
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        if (image != nil)
        {
            return image!
        }
        return UIImage()
    }
}

// Old Swift

extension UIView {

    func takeScreenshot() -> UIImage {

        // Begin context
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.mainScreen().scale)

        // Draw view in that context
        drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)

        // And finally, get image
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }
}

解释这些参数的作用:

  

UIGraphicsBeginImageContextWithOptions()创建临时呈现   绘制原文的上下文。第一个参数size是   缩放图像的目标大小。第二个参数isOpaque是   用于确定是否呈现Alpha通道。设置这个   对于没有透明度的图像(即alpha通道)可能为false   产生带有粉红色调的图像。第三个参数比例是   显示比例因子。设置为0.0时,主要的比例因子   屏幕用于Retina显示为2.0或更高(3.0   iPhone 6 Plus)。

更多相关信息http://nshipster.com/image-resizing/

至于绘制调用,Apple Docs会详细说明herehere

答案 1 :(得分:13)

swift 4和iOS 10 +

extension UIView {

  func screenshot() -> UIImage {
    return UIGraphicsImageRenderer(size: bounds.size).image { _ in
      drawHierarchy(in: CGRect(origin: .zero, size: bounds.size), afterScreenUpdates: true)
    }
  }

}

答案 2 :(得分:2)

Alessandro's answer的替代方法,更简洁,更快速:

extension UIView {

    var snapshot: UIImage {
        return UIGraphicsImageRenderer(size: bounds.size).image { _ in
            drawHierarchy(in: bounds, afterScreenUpdates: true)
        }
    }

}

答案 3 :(得分:1)

 For Taking Screen Short Use This Solution. Hear I can Done How to Take Screen Short UIView with UIImage..

let img = self.captureScreen() // CaptureScreen Is A Function
        let someNSDate = NSDate()
        let myTimeStamp = someNSDate.timeIntervalSince1970
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let documentsDirectory = paths[0]

    if let data = UIImageJPEGRepresentation(img, 0.8)
                {
                    let filename = documentsDirectory.appendingPathComponent("Img_\(myTimeStamp).jpeg")
                    SavedImage_Ary.insert("Img_\(myTimeStamp).jpeg", at: 0) // SavedImage Is A NSMutableArray Where You Can Store your Image
                    //print(SavedImage_Ary)
                    try? data.write(to: filename)
                    UserDefaults.standard.setValue(SavedImage_Ary, forKey: "Saved_Image")
                    Save_Img = true
                    //            self.dismiss(animated: true, completion: nil)
                    Select_Flag = "textdata"
                    let vc = self.storyboard?.instantiateViewController(withIdentifier: "photovc") as! UINavigationController
                    self.present(vc, animated: true, completion: nil)
                }


// MARK : Function

 func captureScreen() -> UIImage
    {

        UIGraphicsBeginImageContextWithOptions(Capture_View.frame.size, false, 0);
        Capture_View.drawHierarchy(in: Capture_View.bounds, afterScreenUpdates: true)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }

答案 4 :(得分:0)

具有后备解决方案的Swift 4.x和iOS 10 +:

extension UIView {
    func screenshot() -> UIImage {
        if #available(iOS 10.0, *) {
            return UIGraphicsImageRenderer(size: bounds.size).image { _ in
                drawHierarchy(in: CGRect(origin: .zero, size: bounds.size), afterScreenUpdates: true)
            }
        } else {
            UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.main.scale)
            drawHierarchy(in: self.bounds, afterScreenUpdates: true)
            let image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
            UIGraphicsEndImageContext()
            return image
        }
    }
}

答案 5 :(得分:0)

func screenShotMethod()->UIImage
    {
        let layer = self.view.layer
        let scale = UIScreen.main.scale
        UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);

        layer.render(in: UIGraphicsGetCurrentContext()!)
        let screenshot = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return screenshot!
    }