我有一个名为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()

屏幕截图的大小符合要求,但它会截取整个视图的屏幕截图,而不仅仅是"概述".

推荐答案

对于一个视图的绘制,只需使用以下命令:

    // 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()

如果您想多次使用它,扩展可能会完成以下任务:

//迅捷4

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()
    }
}

//老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()创建临时呈现

更多信息请点击这里

至于抽签,Apple Docs将其解释为细节herehere

Swift相关问答推荐

在列表项内的NavigationLink中的按钮无法正常工作

如何分解阿拉伯字母?

如何偏移HStack中的视图,但仍然约束框架以与偏移匹配?

';NSInternal不一致异常';,原因:';可见导航栏Xcode 15.0 Crash请求布局

使用 @resultBuilder 的通用 buildList 函数

仅当 boolean 为真时才实现方法(application:didReceiveRemoteNotification)

Swiftui 按钮依次显示一组图像

SwiftUI:决定键盘重叠的内容

如何以快速 Select 器菜单样式调整图像大小

RxSwift:share() 替代方案,保证upstream 的单一订阅

如何使用 Swift/iOS 为人类书写的笔画制作动画?

Swiftwhere数组扩展

在 iOS 中使用 Swift 保存 PDF 文件并显示它们

调整文本的字体大小以适应 UIButton

不能从非开放类继承 swift

如何在 Swift 中使用 Crashlytics 登录?

如何在 SwiftUI 中创建带有图像的按钮?

如何在 Swift 中将 NSURL 转换为字符串

如何在 Swift 中重写 setter

快速延迟加载属性