如何拍摄部分屏幕截图并保存到相机胶卷?



我正在构建一个简单的激励应用程序 - 我的宠物项目。很简单。当按下按钮时,它会打印随机的激励信息。

我希望用户能够按下一个按钮并在屏幕上裁剪激励信息本身并将其保存到相机胶卷中。

找到了一个可以做我想要的教程,但它需要完整屏幕截图和部分屏幕截图。

我正在尝试修改代码,因此只需要部分屏幕截图。

这是Xcode:

    print("SchreenShot")
    // Start full screenshot
    UIGraphicsBeginImageContext(view.frame.size)
    view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
    var sourceImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    UIImageWriteToSavedPhotosAlbum(sourceImage,nil,nil,nil)
    //partial Screen Shot
    print("partial ss")
    UIGraphicsBeginImageContext(view.frame.size)
    sourceImage.drawAtPoint(CGPointMake(0, -100))
    var croppedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    UIImageWriteToSavedPhotosAlbum(croppedImage,nil,nil,nil)

此外,在部分屏幕截图中,它从上到下拍摄 100 像素的"页面"快照。如何让它拍摄页面内容的快照,例如从页面顶部 100 像素到页面底部 150 像素?

非常感谢!

示例代码将视图绘制到图形上下文(快照)中,对其进行裁剪并保存。 我正在通过一些额外的评论对其进行一些更改,因为看起来您是此API的新手

    // Declare the snapshot boundaries
    let top: CGFloat = 100
    let bottom: CGFloat = 150
    // The size of the cropped image
    let size = CGSize(width: view.frame.size.width, height: view.frame.size.height - top - bottom)
    // Start the context
    UIGraphicsBeginImageContext(size)
    // we are going to use context in a couple of places
    let context = UIGraphicsGetCurrentContext()!
    // Transform the context so that anything drawn into it is displaced "top" pixels up
    // Something drawn at coordinate (0, 0) will now be drawn at (0, -top)
    // This will result in the "top" pixels being cut off
    // The bottom pixels are cut off because the size of the of the context
    CGContextTranslateCTM(context, 0, -top)
    // Draw the view into the context (this is the snapshot)
    view.layer.renderInContext(context)
    let snapshot = UIGraphicsGetImageFromCurrentImageContext()
    // End the context (this is required to not leak resources)
    UIGraphicsEndImageContext()
    // Save to photos
    UIImageWriteToSavedPhotosAlbum(snapshot, nil, nil, nil)

最新更新