如何通过给定边界来修剪 NSImage

Tom*_*hen 2 macos nsimage

我有一个 NSImage 对象,我有一个 CIDetector 对象,用于检测该图像上的 QR 代码。检测到后,我想修剪该图像,使其中只包含二维码。这就是我获得二维码边界的方法:

NSArray *features = [myQRDetector featureInImage:myCIImage];
CIQRCodeFeature *qrFeature = features[0];
CGRect qrBounds = qrFeature.bounds;
Run Code Online (Sandbox Code Playgroud)

现在我如何修剪图像,使其仅包含qrBounds变量描述的区域。

onm*_*133 5

在 Swift 5 中

func trim(image: NSImage, rect: CGRect) -> NSImage {
    let result = NSImage(size: rect.size)
    result.lockFocus()

    let destRect = CGRect(origin: .zero, size: result.size)
    image.draw(in: destRect, from: rect, operation: .copy, fraction: 1.0)

    result.unlockFocus()
    return result
}
Run Code Online (Sandbox Code Playgroud)