我想捕捉屏幕的一小部分区域的快照并对其应用模糊 - 尽管速度为60fps - 这对于此代码是不可能的:
let rectangle = CGRect(x: -37, y: -153, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
captureSnapShotWithGaussianBlur(rect: rectangle)
public func captureSnapShotWithGaussianBlur(rect: CGRect) -> UIImage {
let SCREEN_SIZE_SCALE_FACTOR = UIScreen.main.scale
let CROPPING_RECT = CGRect(x: 0, y: 0, width: 118*SCREEN_SIZE_SCALE_FACTOR, height: 66*SCREEN_SIZE_SCALE_FACTOR)
UIGraphicsBeginImageContextWithOptions(CGSize(width: 118, height: 66), true, 0.0)
backgroundView!.drawHierarchy(in: rect, afterScreenUpdates: true)
let capturedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
let ciimage: CIImage = CIImage(image: capturedImage)!
UIGraphicsEndImageContext()
let gaussianfilter: CIFilter = CIFilter(name:"CIGaussianBlur")!
gaussianfilter.setDefaults()
gaussianfilter.setValue(ciimage, forKey: kCIInputImageKey)
gaussianfilter.setValue(10, forKey: kCIInputRadiusKey)
let outputImage: CIImage = gaussianfilter.outputImage!
let finalImage: UIImage = UIImage(ciImage: outputImage.cropping(to: CROPPING_RECT), scale: SCREEN_SIZE_SCALE_FACTOR, orientation: UIImageOrientation.up)
return finalImage
}
我在代码中看到的一个问题是我认为高斯模糊应用于整个图像(因为用于drawHierarchy矩形的UIScreen.main.bounds)。
我希望有一种方法可以执行屏幕的resizableSnapshotView(),然后在该视图中执行drawHierarchy并提取图像 - 唉,这不起作用(虽然它似乎在模拟器中,但不是在电话,它只是呈现黑色)。
有关如何制作更高效的捕捉和模糊方法的任何建议?
干杯!
答案 0 :(得分:0)
尝试使用此扩展程序对视图进行快照并将其模糊,它似乎适用于模拟器和设备:
extenstion UIView {
/// A more efficient way to snapshot a UIView other than UIView.snapshot
///
/// - Returns: UIImage representing the snapshot of the UIView
public func snapshotImage() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
drawHierarchy(in: bounds, afterScreenUpdates: false)
let snapshotImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return snapshotImage
}
public func snapshotView() -> UIView? {
if let snapshotImage = snapshotImage() {
return UIImageView(image: snapshotImage)
} else {
return nil
}
}
}