简体   繁体   English

如何使用Swift以编程方式粘贴图像?

[英]How do I paste an image programmatically with Swift?

I have a working code where I copy an image to UIPasteboard, but I cannot find a way to implement the PASTE functionality programmatically. 我有一个工作代码,可以在其中将图像复制到UIPasteboard,但是我找不到找到以编程方式实现PASTE功能的方法。 Any idea or tip? 有什么想法或建议吗?

The following piece of code might work. 以下代码可能有效。 Make sure you are testing on the device. 确保您正在设备上进行测试。

let image = UIImage(named: "person.png")
UIPasteboard.generalPasteboard().image = image;

based on the comment, you can do it as follows. 根据评论,您可以执行以下操作。 I am putting here the objective-c code, I hope you could get the idea then convert it to the swift. 我在这里输入了Objective-C代码,希望您能理解然后将其转换为快速方法。

NSData* pasteData = [[UIPasteboard generalPasteboard] dataForPasteboardType:(NSString*)kUTTypeJPEG];

you may find the swift solution in the following url Swift UIPasteboard not copying PNG 您可能会在以下网址中找到快速解决方案Swift UIPasteboard不复制PNG

Alternatively, you may use NSData. 或者,您可以使用NSData。 It works on Simulator too. 它也可以在模拟器上使用。

// Copy
let image = UIImage(named: "sample")
let imageData = UIImageJPEGRepresentation(image!, 1)
UIPasteboard.general.setData(imageData!, forPasteboardType: "image")

// Paste
let imageData = UIPasteboard.general.data(forPasteboardType: "image")
let image = UIImage(data:imageData!)
copiedImage.image = image

Swift 3 迅捷3

If an imaged has been copied from another application (eg Safari) this is how I add it into my app. 如果图像是从其他应用程序(例如Safari)复制的,这就是我将其添加到应用程序中的方式。 I trigger this from a UIAlertController as a UIAlertAction. 我从UIAlertController作为UIAlertAction触发了此操作。

let pasteboard = UIPasteboard.general
if pasteboard.hasImages {
     myImage.image = pasteboard.image
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM