我有以下代码在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).你不需要处理像素的好处
原文链接:/swift/319975.htmlclass 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,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()