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

时间:2018-10-12 10:41:25

标签: 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 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)!
    }
}

我遇到的问题是,此函数将渲染与屏幕本身具有相同尺寸的图像。

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

1 个答案:

答案 0 :(得分:0)

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

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的内容按原始大小的三倍保存到数据对象中。