Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Swift 3中向图像添加文本?_Swift_Swift3_Avfoundation_Core Image - Fatal编程技术网

如何在Swift 3中向图像添加文本?

如何在Swift 3中向图像添加文本?,swift,swift3,avfoundation,core-image,Swift,Swift3,Avfoundation,Core Image,我有一个基本的相机应用程序。当我拍摄一张照片时,该图像随后被传递到下面的控制器中。我希望能够向传入的图像中添加文本,以及在视图中拖动文本、缩放文本等。但我甚至无法通过向图像中实际添加文本。我在网上尝试了很多现代教程,但什么都没有 有人能举个例子吗 class PhotoViewController: UIViewController { override var prefersStatusBarHidden: Bool { return true } var lastPoint =

我有一个基本的相机应用程序。当我拍摄一张照片时,该图像随后被传递到下面的控制器中。我希望能够向传入的图像中添加文本,以及在视图中拖动文本、缩放文本等。但我甚至无法通过向图像中实际添加文本。我在网上尝试了很多现代教程,但什么都没有

有人能举个例子吗

class PhotoViewController: UIViewController {


override var prefersStatusBarHidden: Bool {
    return true
}

var lastPoint = CGPoint.zero
var red: CGFloat = 1.0
var green: CGFloat = 1.0
var blue: CGFloat = 1.0
var brushWidth: CGFloat = 10.0
var opacity: CGFloat = 1.0
var swiped = false

var backgroundImage: UIImage?

let backgroundImageView = UIImageView()

override func viewDidLoad() {
    super.viewDidLoad()

    backgroundImageView.frame = self.view.frame
    backgroundImageView.contentMode = UIViewContentMode.scaleAspectFit
    backgroundImageView.isUserInteractionEnabled = true

    self.view.backgroundColor = UIColor.black
    backgroundImageView.image = backgroundImage
    view.addSubview(backgroundImageView)

    let backButton: UIButton = UIButton(frame: CGRect(x: 20, y: 20, width: 25, height: 25))
    let image = UIImage(named: "back_button")
    backButton.setImage(image, for: .normal)
    backButton.addTarget(self, action: #selector(handleBackButton), for: .touchUpInside)
    view.addSubview(backButton)

    let postButton = UIButton(type: .system)
    postButton.setTitle("Post", for: .normal)
    postButton.addTarget(self, action: #selector(uploadPost), for: .touchUpInside)
    view.addSubview(postButton)

    _ = postButton.anchor(nil, left: nil, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 12, rightConstant: 12, widthConstant: 50, heightConstant: 50)

    let saveImageButton = UIButton(type: .system)
    let saveImageButtonImage = UIImage(named: "save_camera")?.withRenderingMode(.alwaysTemplate)
    saveImageButton.setImage(saveImageButtonImage, for: .normal)
    saveImageButton.tintColor = .white
    saveImageButton.addTarget(self, action: #selector(handleSaveImage), for: .touchUpInside)
    view.addSubview(saveImageButton)

    _ = saveImageButton.anchor(nil, left: view.leftAnchor, bottom: view.bottomAnchor, right: nil, topConstant: 0, leftConstant: 12, bottomConstant: 12, rightConstant: 0, widthConstant: 50, heightConstant: 50)
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = false
    if let touch = touches.first {
        lastPoint = touch.location(in: self.view)
    }
}

func drawLine(from fromPoint: CGPoint, to toPoint: CGPoint) {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0)

    backgroundImageView.image?.draw(in: view.bounds)

    let context = UIGraphicsGetCurrentContext()

    context?.move(to: fromPoint)
    context?.addLine(to: toPoint)

    context?.setLineCap(CGLineCap.round)
    context?.setLineWidth(brushWidth)
    context?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
    context?.setBlendMode(CGBlendMode.normal)
    context?.strokePath()

    backgroundImageView.image = UIGraphicsGetImageFromCurrentImageContext()
    backgroundImageView.alpha = opacity
    UIGraphicsEndImageContext()
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = true
    if let touch = touches.first {
        let currentPoint = touch.location(in: view)
        drawLine(from: lastPoint, to: currentPoint)

        lastPoint = currentPoint
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if !swiped {
        // draw a single point
        self.drawLine(from: lastPoint, to: lastPoint)
    }
}
类PhotoViewController:UIViewController{
覆盖变量prefersStatusBarHidden:Bool{
返回真值
}
var lastPoint=CGPoint.zero
变量红色:CGFloat=1.0
绿色变量:CGFloat=1.0
蓝色变量:CGFloat=1.0
变量刷宽:CGFloat=10.0
变量不透明度:CGFloat=1.0
var swiped=false
var背景图像:UIImage?
让backgroundImageView=UIImageView()
重写func viewDidLoad(){
super.viewDidLoad()
backgroundImageView.frame=self.view.frame
backgroundImageView.contentMode=UIViewContentMode.ScaleSpectFit
backgroundImageView.isUserInteractionEnabled=true
self.view.backgroundColor=UIColor.black
backgroundImageView.image=背景图像
view.addSubview(backgroundImageView)
let backButton:UIButton=UIButton(帧:CGRect(x:20,y:20,宽度:25,高度:25))
让image=UIImage(名为:“后退按钮”)
backButton.setImage(图像,用于:。正常)
backButton.addTarget(self,action:#选择器(handleBackButton),用于:。touchUpInside)
view.addSubview(backButton)
让postButton=UIButton(类型:。系统)
postButton.setTitle(“Post”,用于:。正常)
postButton.addTarget(self,action:#选择器(uploadPost),for:.touchUpInside)
view.addSubview(postButton)
_=postButton.anchor(零,左:零,底部:view.bottomAnchor,右:view.rightAnchor,顶部常数:0,左常数:0,底部常数:12,右常数:12,宽度常数:50,高度常数:50)
让saveImageButton=UIButton(类型:。系统)
让saveImageButtonImage=UIImage(名为:“save_camera”)?。使用渲染模式(.alwaysTemplate)
saveImageButton.setImage(saveImageButtonImage,用于:。正常)
saveImageButton.tintColor=.white
saveImageButton.addTarget(self,action:#选择器(handleSaveImage),用于:.touchUpInside)
view.addSubview(saveImageButton)
_=saveImageButton.anchor(零,左:view.leftAnchor,下:view.bottomAnchor,右:零,顶部常数:0,左常数:12,底部常数:12,右常数:0,宽度常数:50,高度常数:50)
}
覆盖func TouchesBegind(Touchs:Set,带有事件:UIEvent?){
刷卡=错误
如果让触摸=先触摸{
lastPoint=touch.location(在:self.view中)
}
}
func绘制线(从起点:CGPoint到地形点:CGPoint){
UIGraphicsBeginImageContextWithOptions(view.bounds.size,false,0)
backgroundImageView.image?.draw(在:view.bounds中)
let context=UIGraphicsGetCurrentContext()
上下文?.move(到:fromPoint)
上下文?.addLine(到:toPoint)
上下文?.setLineCap(CGLineCap.round)
上下文?.setLineWidth(笔刷宽度)
上下文?.setStrokeColor(红色:红色,绿色:绿色,蓝色:蓝色,alpha:1.0)
上下文?.setBlendMode(CGBlendMode.normal)
上下文?.strokePath()
backgroundImageView.image=UIGraphicsGetImageFromCurrentImageContext()
backgroundImageView.alpha=不透明度
UIGraphicsSendImageContext()
}
覆盖功能触摸移动(touchs:Set,带有事件:UIEvent?){
刷卡=正确
如果让触摸=先触摸{
让currentPoint=触摸位置(在:视图中)
抽绳(从:最后一点到:当前点)
lastPoint=currentPoint
}
}
覆盖函数touchesend(touchs:Set,带有事件:UIEvent?){
如果!刷卡{
//画一个点
自绘制线(起点:lastPoint,终点:lastPoint)
}
}

没有简单的方法可以做到这一切,但这里有一些代码可以帮助您应对第一次挑战

class ViewController: UIViewController {

    @IBOutlet weak var storyboardImageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        if let image = createFinalImageText() {
            storyboardImageView.image = image
        }
    }

    func createFinalImageText () -> UIImage? {

        let image = UIImage(named: "bear.jpeg")

        let viewToRender = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.width)) // here you can set the actual image width : image.size.with ?? 0 / height : image.size.height ?? 0

        let imgView = UIImageView(frame: viewToRender.frame)

        imgView.image = image

        viewToRender.addSubview(imgView)

        let textImgView = UIImageView(frame: viewToRender.frame)

        textImgView.image = imageFrom(text: "Example text", size: viewToRender.frame.size)

        viewToRender.addSubview(textImgView)

        UIGraphicsBeginImageContextWithOptions(viewToRender.frame.size, false, 0)
        viewToRender.layer.render(in: UIGraphicsGetCurrentContext()!)
        let finalImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return finalImage
    }

    func imageFrom(text: String , size:CGSize) -> UIImage {

        let renderer = UIGraphicsImageRenderer(size: size)
        let img = renderer.image { ctx in
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.alignment = .center

            let attrs = [NSFontAttributeName: UIFont(name: "HelveticaNeue", size: 36)!, NSForegroundColorAttributeName: UIColor.white, NSParagraphStyleAttributeName: paragraphStyle]

            text.draw(with: CGRect(x: 0, y: size.height / 2, width: size.width, height: size.height), options: .usesLineFragmentOrigin, attributes: attrs, context: nil)

        }
        return img
    }
}


我希望这会有所帮助。

您链接的教程中有一个使用
NSString.draw()的好例子
在图像上绘制文本。当您尝试时发生了什么?您可以去,也可以去,或者我尝试了以上所有操作,但什么都没有。我在图像上什么都没有。非常奇怪……感谢您的帮助!Chels,您对下面收到的答案了解得如何?