[英]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.