Swift 将CALayer渲染为具有任意大小的图像

Swift 将CALayer渲染为具有任意大小的图像,swift,macos,core-graphics,calayer,Swift,Macos,Core Graphics,Calayer,我在macOS应用程序中使用以下CALayer扩展将CALayer渲染成图像: extension CALayer { /// Get `Data` representation of the layer. /// /// - Parameters: /// - fileType: The format of file. Defaults to PNG. /// - properties: A dictionary that contains k

我在macOS应用程序中使用以下
CALayer
扩展将
CALayer
渲染成图像:

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: NSBitmapImageRep.FileType = .png, properties: [NSBitmapImageRep.PropertyKey : 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: NSColorSpaceName.deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
        imageRepresentation.size = bounds.size

        let context = NSGraphicsContext(bitmapImageRep: imageRepresentation)!

        render(in: context.cgContext)

        return imageRepresentation.representation(using: fileType, properties: properties)!
    }
}
我遇到的问题是,这个函数渲染的图像与屏幕上渲染的层本身具有相同的尺寸


如何修改它以指定要渲染的图像的大小,并使层扩展到图像的尺寸?

您必须为所需的大小添加一个附加参数,并将内容缩放到该尺寸:

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

    let context = NSGraphicsContext(bitmapImageRep: imageRepresentation)!

    context.cgContext.scaleBy(x: size.width / width, y: size.height / height)
    render(in: context.cgContext)

    return imageRepresentation.representation(using: fileType,
        properties: properties)!
}
通过此修改,您可以调用此方法,如下所示:

let theBounds = myView.bounds
let theSize = CGSize(width: theBounds.width * 3.0, height: theBounds.height * 3.0)
let theData = myView.layer?.data(using: .png, size: theSize, properties: [:])

myView
的内容按原始大小的三倍放大保存到数据对象中

我非常希望这能起作用,但我把它注入到我的代码中,它产生了一个缩小的图像。我试图实现的是基于UI中的一组层构建一个世界地图,然后将该组件的视图导出到可以设置为墙纸的图像中。我在这里的公共项目中注入了您的代码:并在这里使用了它:如果您想创建一个放大的图像,只需在调用中更改大小即可。我已经改变了我的示例。我已经尝试过了,但出于某种原因,它似乎渲染了一个大小合适的图像,但该层仅在左下角渲染。