我正在寻找一种渲染CALayer或NSView并重新获得NSImage的方法。
我有一个自定义类,它是NSView的子类。
一开始,我只是简单地制作了一个渐变层来覆盖NSView。

class ContentView: NSView {

   override func draw(_ dirtyRect: NSRect) {
      fillGradientLayer()
   }

   func fillGradientLayer() {
      gradientLayer = CAGradientLayer()
      gradientLayer.colors = [#colorLiteral(red: 0, green: 0.9909763549, blue: 0.7570167824, alpha: 1),#colorLiteral(red: 0, green: 0.4772562545, blue: 1, alpha: 1)].map({return $0.cgColor})
      gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
      gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
      gradientLayer.frame = self.frame.insetBy(dx: margin, dy: margin)
      gradientLayer.zPosition = 2
      gradientLayer.name = "gradientLayer"
      gradientLayer.contentsScale = (NSScreen.main()?.backingScaleFactor)!
      self.layer?.addSublayer(gradientLayer)
   }
}
在某个时候,我想从CALayers获取NSImage(或CGImage)。
我在Internet上找到了一些样本,并将其转换为:
extension CALayer {

func getBitmapImage() -> NSImage {

    let btmpImgRep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(self.frame.width), pixelsHigh: Int(self.frame.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSDeviceRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0)

    let  image: NSImage = NSImage(size: self.frame.size)
    image.lockFocus()
    let ctx = NSGraphicsContext(bitmapImageRep: btmpImgRep!)
    let cgCtxt = ctx!.cgContext

    self.render(in: cgCtxt)
    cgCtxt.draw(layer: CGLayer, in: CGRect)

    image.unlockFocus()
    return image
  }
}
第一个问题是 draw(层:CGLayer,在:CGRect中)方法需要CGLayer而不是CALayer。
其次,我不知道最终生成的代码是否最终会渲染我的图层,或者我做错了什么。
谢谢你的帮助。

编辑:
从CALayer获取CGImage的解决方案。
extension CALayer {

func getBitmapImage() -> NSImage {

    let btmpImgRep =
        NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(self.frame.width), pixelsHigh: Int(self.frame.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSDeviceRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 32)

    let ctx = NSGraphicsContext(bitmapImageRep: btmpImgRep!)
    let cgContext = ctx!.cgContext

    self.render(in: cgContext)

    let cgImage = cgContext.makeImage()

    let nsimage = NSImage(cgImage: cgImage!, size: CGSize(width: self.frame.width, height: self.frame.height))

        return nsimage
  }
}
如何从NSView获取NSImage在下面的答案中。
P.S.我对NSBitmapImageRep属性了解不多,所以这部分可能是错误的。

最佳答案

以下是一些NSView选项:

extension NSView {

    /// Get `NSImage` representation of the view.
    ///
    /// - Returns: `NSImage` of view

    func image() -> NSImage {
        let imageRepresentation = bitmapImageRepForCachingDisplay(in: bounds)!
        cacheDisplay(in: bounds, to: imageRepresentation)
        return NSImage(cgImage: imageRepresentation.cgImage!, size: bounds.size)
    }

}

或者
extension NSView {

    /// Get `Data` representation of the view.
    ///
    /// - Parameters:
    ///   - fileType: The format of file. Defaults to PNG.
    ///   - properties: A dictionary that contains key-value pairs specifying image properties.
    /// - Returns: `Data` for image.

    func data(using fileType: NSBitmapImageFileType = .PNG, properties: [String : Any] = [:]) -> Data {
        let imageRepresentation = bitmapImageRepForCachingDisplay(in: bounds)!
        cacheDisplay(in: bounds, to: imageRepresentation)
        return imageRepresentation.representation(using: fileType, properties: properties)!
    }

}

一些CALayer选项:
extension CALayer {

    /// Get `NSImage` representation of the layer.
    ///
    /// - Returns: `NSImage` of the layer.

    func image() -> NSImage {
        let width = Int(bounds.width * self.contentsScale)
        let height = Int(bounds.height * self.contentsScale)
        let imageRepresentation = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: width, pixelsHigh: height, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSDeviceRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0)!
        imageRepresentation.size = bounds.size

        let context = NSGraphicsContext(bitmapImageRep: imageRepresentation)!

        render(in: context.cgContext)

        return NSImage(cgImage: imageRepresentation.cgImage!, size: bounds.size)
    }

}

或者
extension CALayer {

    /// Get `Data` representation of the layer.
    ///
    /// - Parameters:
    ///   - fileType: The format of file. Defaults to PNG.
    ///   - properties: A dictionary that contains key-value pairs specifying image properties.
    ///
    /// - Returns: `Data` for image.

    func data(using fileType: NSBitmapImageFileType = .PNG, properties: [String : Any] = [:]) -> Data {
        let width = Int(bounds.width * self.contentsScale)
        let height = Int(bounds.height * self.contentsScale)
        let imageRepresentation = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: width, pixelsHigh: height, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSDeviceRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0)!
        imageRepresentation.size = bounds.size

        let context = NSGraphicsContext(bitmapImageRep: imageRepresentation)!

        render(in: context.cgContext)

        return imageRepresentation.representation(using: fileType, properties: properties)!
    }

}

关于swift - 从CALayer或NSView获取图像(swift 3),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41386423/

10-11 19:27