本文介绍了根据 UIImage 大小截屏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在捕获自定义视图时遇到问题.我正在尝试使用 UIImage 图像数据的大小设置捕获的图像,但是当我截取屏幕截图时,图像是这样的!:

I have problem with capture a custom view. I am trying to set captured image with size UIImage image data's size, but when I take the screenshot the image goes like this ! :

图片缩小了!这是代码:

The image shrinks ! Here is the code :

  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)

仍然没有成功

编辑

我试过这个方法,捕获然后裁剪它但仍然没有成功

I tried this method, captured and then crop it but still no success

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

但是图像会失真:

推荐答案

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

I've tried to capture screenshot of imageview with aspectToFit content mode & having no constant width & height with below method

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),即图像的原始大小.

& returned screenshot has same image size (229*220) which is original size of image.

这篇关于根据 UIImage 大小截屏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 00:02