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

标签 swift swift3 avfoundation core-image

我有一个基本的相机应用程序。当我拍照时,该图像会传递到下面的 Controller 中。我希望能够向传入的图像添加文本以及将其拖动到 View 周围、缩放它等,但我什至无法通过实际向图像添加文本。我在网上试过很多现代教程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)
    }
}

最佳答案

完成这一切没有简单的方法,但这里有一些代码可以应对您的第一个挑战。

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

希望对您有所帮助。

关于swift - 如何在 Swift 3 中向图像添加文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44092046/

相关文章:

ios - 如何在 Swift 中使用 UIDatePicker?

ios - UIPickerView 获取另一个 UIPickerView 的值

swift - Spritekit 水平 ScrollView

cocoa - applicationDidFinishLaunching 未调用,使用 Storyboards 和 swift3

ios - 使用 PHP 在 Objective-C 中上传录制的音频文件

ios - 扫描的 Barcode Swift 中的 Unicode 字符

swift - CloudKit 与沙箱用户同步测试

xcode - 照片框架 - contentMode 错误

ios - Release-iphonesimulator 中有很多文件 "missing from working copy"

ios - 线程1:EXC_BAD_ACCESS(代码= 1,地址= 0x48)avaudiofoundation