I use the following code to draw a text on an NSImage
func drawText(image :NSImage) ->NSImage
{
let text = text
let font = NSFont(name:String(combo_font.stringValue), size: 50)
let imageRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
let fontAttributes = [NSAttributedStringKey.font: font]
let fontsize = (text as NSString).size(withAttributes: fontAttributes)
let textRect = CGRect(x: (image.size.width/2-fontsize.width/2), y: image.size.height/2, width: fontsize.width, height: fontsize.height)
let textStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
let textFontAttributes = [
NSAttributedStringKey.font: font,
NSAttributedStringKey.foregroundColor: NSColor.white,
NSAttributedStringKey.paragraphStyle: 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: NSColorSpaceName.calibratedRGB, bytesPerRow: 0, bitsPerPixel: 0)!
im.addRepresentation(rep)
im.lockFocus()
image.draw(in: imageRect)
text.draw(in: textRect, withAttributes: textFontAttributes)
im.unlockFocus()
return im
}
To prevent UI Freezing i do the long running operation in background thread
override func controlTextDidChange(_ obj: Notification) {
if(obj.object is NSTextField)
{
let textdata=obj.object as! NSTextField
if(txtfield.identifier?.rawValue=="txt_field")
{
self.textdata=self.txtbox.stringValue
DispatchQueue.global().async {
self.img_view.image=self.drawText(image: NSImage(byReferencingFile: self.selectedfilename)!);
}
}
}
}
When processing an Image of 391KB in size, the process takes too long to update the UI.How can i improve the performance.I just need to display the preview to the user,resizing image to a smaller size is also an option to improve the performance;But the same look should be achieved in full resolution image as well when processing later.