我有以下代码在NSImage上绘制文本。但是,当我将其保存到磁盘时,生成的图像将被调整为较小的尺寸。
我做错了什么?请指教
func drawText(image :NSImage) ->NSImage { let text = "Sample Text" let font = NSFont.boldSystemFont(ofSize: 18) let imageRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height) let textRect = CGRect(x: 5, y: 5, width: image.size.width - 5, height: image.size.height - 5) let textStyle = NSMutableParagraphStyle.default().mutableCopy() as! NSMutableParagraphStyle let textFontAttributes = [ NSFontAttributeName: font, NSForegroundColorAttributeName: NSColor.white, NSParagraphStyleAttributeName: textStyle ] let im:NSImage = NSImage(size: image.size) let rep:NSBitmapImageRep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(image.size.width), pixelsHigh: Int(image.size.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0)! im.addRepresentation(rep) im.lockFocus() image.draw(in: imageRect) text.draw(in: textRect, withAttributes: textFontAttributes) im.unlockFocus() return im }
这是另一种使用临时NSView方法绘制图像和文本并将结果缓存到新图像中的方法(代码为Swift 4)。您无需处理像素的好处
NSView
class ImageView : NSView { var image : NSImage var text : String init(image: NSImage, text: String) { self.image = image self.text = text super.init(frame: NSRect(origin: NSZeroPoint, size: image.size)) } required init?(coder decoder: NSCoder) { fatalError() } override func draw(_ dirtyRect: NSRect) { let font = NSFont.boldSystemFont(ofSize: 18) let textRect = CGRect(x: 5, y: 5, width: image.size.width - 5, height: image.size.height - 5) image.draw(in: dirtyRect) text.draw(in: textRect, withAttributes: [.font: font, .foregroundColor: NSColor.white]) } var outputImage : NSImage { let imageRep = bitmapImageRepForCachingDisplay(in: frame)! cacheDisplay(in: frame, to:imageRep) let tiffData = imageRep.tiffRepresentation! return NSImage(data : tiffData)! } }
要使用它,初始化一个视图
let image = ... // get some image let view = ImageView(image: image, text: "Sample Text")
并获得新的形象
let imageWithText = view.outputImage
注意:
根本不使用段落样式,但是如果要创建可变的段落样式,只需编写
let textStyle = NSMutableParagraphStyle()