swift - 如何将从用户处获取的文本添加到图像中?

标签 swift uiimageview uilabel

我正在尝试将文本添加到从用户处获取的图像中。

在第一个 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/

相关文章:

ios - 通过搜索 LinkedIn 获取公开资料 URL

iphone - 插入 subview :belowSubview: for a UIImageView

ios - 如何观察图像旋转?

ios - UILabel 更新了文字,但旧的内容还在屏幕上

objective-c - UILabel中如何控制行距

ios - Json 数据未正确反射(reflect)在 tableView 中

swift - 原始类型 'Bool' 不能用任何文字表达

ios - 快速从多个 View 获取数据

ios - swift UIActivityView stopAnimating() 不工作

objective-c - 卡住试图从一个 Viewcontroller 中的 UILabel 获取 NSString 以放置在另一个 Viewcontroller 的 UITextView 中