我刚刚开始编程。在保存图像之前,我试图在用 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
}
如有任何帮助,我们将不胜感激。
最佳答案
我已经修改了你的代码..试试这个..
@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);
}
}
关于ios - 在 iPhone 上拍照并在 Swift 中保存之前永久覆盖文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33360244/