Scaling NSTextAttachment in NSPasteboard

故事扮演 提交于 2019-12-11 04:14:27

问题


I have an NSTextAttachment which contains an NSImage. What I would like to do is scale this image so that it's smaller in dimensions but will keeping the same number of pixels. Then moving it to the general pasteboard. Once it's pasted (into whatever app) I would like it to paste with the same dimensions I just set. The problem I am having is that pasting it in any other app always puts it at is original dimensions. I have tried the following things and none seem to fully work

First is simply resizing the image and then copying. This retains the proper dimensions (let's say 100 x 100 pt) but the image is very blurry and the resolution is 72 dpi.

//variable im is an NSImage object that is present
//variable newsize is an NSSize which is calculated to give the image proper resolution

im.lockFocus()
im.size = newsize 
im.unlockFocus()

The second thing I have tried is use the techniques listed on this page. None of which do anything once I paste the TextAttachment to another app (such as Pages for example). Subclassing NSTextAttachment has no effect. Also changing the bounds of the attachment seems to have no effect once it's pasted.

The last thing I tried is after the iterating through the NSAttributedString which holds the attachments, and setting each one's bounds. Still no effect when pasting into other apps.

So the ultimate question: is there a way to have a scaled NSImage inside and NSTextAttachment copy to the clipboard?

func copy() {
    let pboard = NSPasteboard.general()
    pboard.clearContents()

    let rtf = NSMutableAttributedString()

    //self.images is an array that contains a bunch of images
    //note that it is required that I use a RTF to copy/paste my images
    //because there is text mixed with the images
    //for simplicity I have removed the text from this code
    //removing it from my app and doing the same code has no effect

    for im in self.images {
        let a = NSTextAttachment() //subclassing NSTextAttachment has no effect on pasted image size
        a.image = im
        a.bounds = NSMakeRect(0,0,100,100) //has no effect on pasted image size

        //if I resize the image prior to copying (using the code above)
        //the pasted image has correct dimensions but is very blurry. 

        let str = NSAttributedString(attachment: a)
        rtf.append(str)
    }

    pboard.writeObjects([rtf])
}

来源:https://stackoverflow.com/questions/40952461/scaling-nstextattachment-in-nspasteboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!