在保存到Swift之前,在iPhone上拍照并永久叠加文本

时间:2015-10-27 05:00:08

标签: ios iphone swift2

我刚开始编程。我想在保存图像之前在用iPhone拍摄的图像上叠加文本。我发现一些代码看起来很有前途,但没有任何具体的工作,没有专门回答这个问题的帖子。这是我拍摄图像的代码。如果没有覆盖文本,我知道它需要一张照片。

@IBAction func handleShutterButton(sender: UIButton) {
    cameraController.captureStillImage { (image, metadata) -> Void in
        self.view.layer.contents = image
        var project = "ProjectX"
        var camNumber = "c01"
        let timestamp = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .MediumStyle, timeStyle: .ShortStyle)
        let overlay = "\(project) \(camNumber) \(timestamp)"
        self.overlayText(overlay, inImage: UIImage(named: image)!, atPoint: CGPointMake(20, 20)) // This is where it fails
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    }
}

这是我用来覆盖文本的功能。

func overlayText(drawText: NSString, inImage: UIImage, atPoint:CGPoint)->UIImage{

    // Setup the font specific variables
    let textColor: UIColor = UIColor.whiteColor()
    let textFont: UIFont = UIFont(name: "Helvetica Bold", size: 12)!

    //Setup the image context using the passed image.
    UIGraphicsBeginImageContext(inImage.size)

    //Setups up the font attributes that will be later used to dictate how the text should be drawn
    let textFontAttributes = [
        NSFontAttributeName: textFont,
        NSForegroundColorAttributeName: textColor,
    ]

    //Put the image into a rectangle as large as the original image.
    inImage.drawInRect(CGRectMake(0, 0, inImage.size.width, inImage.size.height))

    // Creating a point within the space that is as big as the image.
    let rect: CGRect = CGRectMake(atPoint.x, atPoint.y, inImage.size.width, inImage.size.height)

    //Now Draw the text into an image.
    drawText.drawInRect(rect, withAttributes: textFontAttributes)

    // Create a new image out of the images we have created
    let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()

    // End the context now that we have the image we need
    UIGraphicsEndImageContext()

    //And pass it back up to the caller.
    return newImage
}

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:2)

我已对您的代码进行了更改..试试这个..

@IBAction func handleShutterButton(sender: UIButton) {

    cameraController.captureStillImage { (image, metadata) -> Void in
        self.view.layer.contents = image
        var project = "ProjectX"
        var camNumber = "c01"
        let timestamp = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .MediumStyle, timeStyle: .ShortStyle)
        let overlay = "\(project) \(camNumber) \(timestamp)"
        var changedImage : UIImage = self.overlayText(overlay, inImage: image, atPoint: CGPointMake(20, 20)) // This is where it fails
        UIImageWriteToSavedPhotosAlbum(changedImage, nil, nil, nil);
    }
}