基于UIImage大小捕获屏幕

时间:2017-07-05 16:42:42

标签: ios iphone swift xcode uiimage

我在捕获自定义视图时遇到问题。我正在尝试设置尺寸为UIImage图像数据大小的捕获图像,但是当我拍摄屏幕截图时,图像就像这样! :

enter image description here

图像缩小! 这是代码:

  UIGraphicsBeginImageContextWithOptions((self.photoImage.size), false, UIScreen.main.scale)

        self.captureView.layer.render(in: UIGraphicsGetCurrentContext()!)

        self.photoToShare = UIGraphicsGetImageFromCurrentImageContext()

        print(self.photoToShare.size) //the size is right 

        UIGraphicsEndImageContext()

        self.photo.image = self.photoToShare!

有什么问题?!

我累了: self.captureView.drawHierarchy(in: self.captureView.bounds , afterScreenUpdates: true)

仍然没有成功

编辑

我尝试了这种方法,捕获然后裁剪但仍未成功

UIGraphicsBeginImageContextWithOptions(self.captureView.bounds.size, false, UIScreen.main.scale)
            self.captureView.drawHierarchy(in: self.captureView.bounds, afterScreenUpdates: true)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            let cropRect = CGRect(x: 0, y: 0, width: (self.photoImage.size.width) , height: (self.photoImage.size.height))
            UIGraphicsBeginImageContextWithOptions(cropRect.size, false, UIScreen.main.scale)
            image?.draw(in: cropRect)
            let finalImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            self.photo.image = finalImage

但图像会失真:

enter image description here

2 个答案:

答案 0 :(得分:0)

我尝试使用aspectToFit内容模式捕获imageview的屏幕截图&没有恒定的宽度&高度与以下方法

func captureShot() {
        let layer : CALayer = self.imageView!.layer
        UIGraphicsBeginImageContextWithOptions((layer.frame.size), false, 1.0);
        layer.render(in: UIGraphicsGetCurrentContext()!)
        let screenshot = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

    }

&安培;返回的屏幕截图具有相同的图像大小(229 * 220),这是图像的原始大小。

enter image description here

答案 1 :(得分:0)

试试这个:

extension UIView {
    var screenCapture: UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, opaque, 0.0)
        drawViewHierarchyInRect(bounds, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

将其放入UImageView:

let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.image = someView.screenCapture
imageView.frame = someFrame
someSuperview.addSubview(imageView)

(抱歉所有some,但希望它不会混淆:)

希望这有帮助!