繁体   English   中英

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

[英]Rendering a CALayer to an image with arbitrary size

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM