Drawing Text over NSImage

I have the following code to draw a text over an NSImage.

But the resulting image is getting cropped at the corner and only the corner portion is displayed.

What i'm i doing wrong? Please advice

funcdrawText(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
}

As far as I tested, your code generates an image with the same size and the same content to the original image, just that a short text added on left-top of the image.


If you see a cropped image, it may be a problem of how you display it. Try your code on the Playground and check what you see.

But upon checking with some images there is some resizing involved.

eg: one with W:1514 and height:2000,The resulting image after drawing the text was much smaller.

Around 364X480 .. Where is this resizing happening in the code.


Were you able to reproduce it? Please advice.

Resizing may be caused by some autolayout.


Have you defined any constraints ?

No.. i simply call this method

var tempimage=orgimg
tempimage=drawText(image: tempimage)

Unfortunately, I cannot reproduce the same issue as you describe with any images I have.


Your input NSImage may be sort of super-natural or you may have some faults in the other hidden parts of your code.

Anyway, with both things unavailable, I cannot think of anything to say as for now.

Drawing Text over NSImage
 
 
Q