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

时间:2017-05-21 00:24:20

标签: swift swift3 avfoundation core-image

我有一个基本的相机应用程序。当我拍照时,该图像然后传递到下面的控制器。我希望能够将文本添加到传入的图像中,并将其拖动到视图周围,缩放等等,但我甚至无法实际将文本添加到图像上。我在线尝试了一堆现代教程like this for example,但没有。

任何人都可以提供示例吗?

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)
    }
}

1 个答案:

答案 0 :(得分:2)

没有简单的方法可以做到这一切,但这里有一些代码可以用于你的第一次挑战。

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
    }
}

enter image description here

我希望这会有所帮助。