NSImage Getting Resized when I draw Text on it

前端 未结 2 389
面向向阳花
面向向阳花 2020-12-18 16:51

I have the following code to draw a text over an NSImage. But the resulting image is getting resized to smaller one when I save it to disk.

What i\'m i doing wrong?

2条回答
  •  萌比男神i
    2020-12-18 17:37

    This is a different approach using a temporary NSView to draw the image and the text and cache the result in a new image (code is Swift 4). The benefit it you don't need to deal with pixels

    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)!
        }
    }
    

    To use it, initialize a view

    let image = ... // get some image
    let view = ImageView(image: image, text: "Sample Text")
    

    and get the new image

    let imageWithText = view.outputImage
    

    Note:

    The paragraph style is not used at all, but if you want to create a mutable paragraph style just write

    let textStyle = NSMutableParagraphStyle()
    

提交回复
热议问题