菜鸟教程小白 发表于 2022-12-11 20:03:10

ios - 以编程方式截取图像


                                            <p><p>我遇到了一种情况,我希望我的代码截取屏幕截图,但只截取屏幕的中间部分。</p>

<pre><code>    @IBAction func savePhoto(_ sender: UIButton) {

    // Does not go into program
    let size = CGSize(width: view.frame.size.width, height: view.frame.size.height)

    UIGraphicsBeginImageContextWithOptions(CGSize(width:1024.0,height: 1024.0), false, UIScreen.main.scale)


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

    UIImageWriteToSavedPhotosAlbum(newImage!, nil, nil, nil)

    }
</code></pre>

<p>我确实尝试将其设置为 1024x1024 的屏幕截图,我认为这会起作用,但事实并非如此。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>试试这个,它对我有用。
希望,有帮助。 </p>

<pre><code>@IBAction func savePhoto(_ sender: UIButton) {

            UIGraphicsBeginImageContextWithOptions(CGSize(width: self.view.frame.size.width, height: self.view.frame.size.height - 100), false, 0.0)
            self.view.drawHierarchy(in: CGRect(x: 0, y: 0, width: 1024.0, height: 1024.0), afterScreenUpdates: true)
            if let image = UIGraphicsGetImageFromCurrentImageContext() {
                UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

            }
            UIGraphicsEndImageContext();

      }
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 以编程方式截取图像,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/49865264/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/49865264/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 以编程方式截取图像