我有以下代码来创建一个 200x200 像素的圆图像。这不是在屏幕上使用,所以我在锁定焦点和绘图之前手动将 NSBitmapImageRep 添加到图像。
let ovalSize = CGSize(width: 200, height: 200)
let ovalPath = NSBezierPath(ovalIn: CGRect(origin: CGPoint.zero, size: ovalSize))
let ovalImage = NSImage(size: ovalSize)
let imageRep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 200, pixelsHigh: 200, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: true, colorSpaceName: .deviceRGB, bitmapFormat: [.alphaFirst, .thirtyTwoBitLittleEndian], bytesPerRow: 0, bitsPerPixel: 0)
ovalImage.addRepresentation(imageRep!)
ovalImage.lockFocus()
NSColor(deviceWhite: 1, alpha: 1).setFill()
ovalPath.fill()
ovalImage.unlockFocus()
但是,如果我快速查看 ovalImage
,它已以 400x400 呈现,并且打印 ovalImage
的表示会产生以下内容:
[<NSCGImageSnapshotRep:0x60000175bf00 cgImage=<CGImage 0x101612d30> (DP)
<<CGColorSpace 0x60000260cba0> (kCGColorSpaceICCBased; kCGColorSpaceModelRGB; Color LCD)>
width = 400, height = 400, bpc = 8, bpp = 32, row bytes = 1600
kCGImageAlphaPremultipliedFirst | kCGImageByteOrder32Little | kCGImagePixelFormatPacked
is mask? No, has masking color? No, has soft mask? No, has matte? No, should interpolate? Yes>]
lockFocus
的文档提到,如果一个表示不可用,将添加一个表示,所以我很困惑为什么要替换我添加的那个?
最佳答案
我想你需要的是"Drawing Offscreen Images Using a Block-Based Drawing Method to Support High Resolution Displays" .
你可以这样做:
let ovalPath = NSBezierPath(ovalIn: CGRect(origin: CGPoint.zero, size: NSMakeSize(200, 200)))
let ovalImage = NSImage(size: NSMakeSize(200, 200), flipped: false) { (rect) -> Bool in
NSColor(deviceWhite: 1, alpha: 1).setFill()
ovalPath.fill()
return true
}
或
let ovalSize = CGSize(width: 200, height: 200)
let ovalPath = NSBezierPath(ovalIn: CGRect(origin: CGPoint.zero, size: NSMakeSize(200, 200)))
let imageRep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 200, pixelsHigh: 200, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: true, colorSpaceName: .deviceRGB, bitmapFormat: [.alphaFirst, .thirtyTwoBitLittleEndian], bytesPerRow: 0, bitsPerPixel: 0)
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: imageRep!)
NSColor(deviceWhite: 1, alpha: 1).setFill()
ovalPath.fill()
NSGraphicsContext.restoreGraphicsState()
let ovalImage = NSImage(size: ovalSize)
ovalImage.addRepresentation(imageRep!)
我不知道您添加的表示被替换的原因,但您应该 treat NSImage and its image representations as immutable objects .
关于swift - 在 NSImage 上使用 lockFocus 时如何强制使用非视网膜图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54560814/