我正在尝试将文本添加到从用户处获取的图像中。
在第一个 View 中,我创建了一个文本字段和一个按钮。无论用户在文本字段中输入什么,然后按下按钮,它都会进入第二个 View ,其中我有 ImageView ,并且我可以使用 UIImagePickerController
设置图像。
我在第二个 View 中有一个标签,其文本设置为 textField.text
。
我可以将该标签拖动到任何我想要的位置。
代码如下:
class SecondView: UIViewController, UINavigationControllerDelegate,UIImagePickerControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
var theLabel : UILabel!
var theText = ""
override func viewDidLoad() {
super.viewDidLoad()
theLabel = UILabel(frame: CGRect(x: self.view.bounds.width/2 - 100, y: self.view.bounds.height/2 - 50, width: 200, height: 100))
theLabel.textAlignment = NSTextAlignment.Center
self.view.addSubview(theLabel)
var gesture = UIPanGestureRecognizer(target: self, action: Selector("dragMe:"))
theLabel.addGestureRecognizer(gesture)
theLabel.userInteractionEnabled = true
theLabel.text = theText
}
func dragMe(gesture : UIPanGestureRecognizer) {
let translation = gesture.translationInView(self.view)
var label = gesture.view!
label.center = CGPoint(x: label.center.x + translation.x, y: label.center.y + translation.y)
gesture.setTranslation(CGPointZero, inView: self.view)
}
@IBAction func pickAnImage(sender: AnyObject) {
var imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
imageView.image = image
var bool = true
self.dismissViewControllerAnimated(bool, completion: nil)
}
现在我想将标签添加到图像中。由于我可以将标签拖动到任何位置,因此我可以将其放置在图像上。
但是如何保存带有文本的图像呢?
我是否遵循错误的方法来获取输出? 有人可以帮我解决这个问题吗?
最佳答案
您需要设置 CGContext 并根据旧图像和渲染文本创建新图像。请参阅https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGContext/index.html
关于swift - 如何将从用户处获取的文本添加到图像中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27456770/