2015-10-27 30 views
0

我剛剛開始編程。我試圖在保存圖像之前疊加使用iPhone拍攝的圖像上的文字。我發現了一些看起來很有希望的代碼,但沒有具體說明這項工作,也沒有專門回答這個問題的文章。這是我拍攝圖像的代碼。如果沒有嘗試覆蓋文本,我知道它會拍攝一張照片。在iPhone上拍照並永久覆蓋文本,然後保存在Swift中

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

任何幫助,將不勝感激。

回答

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); 
    } 
} 
+0

仍然得到同樣的錯誤 - 無法將類型的價值「的UIImage」預期參數類型「字符串」。哎呀。我應該在原文中添加錯誤。 – user3118171

+0

plz檢查更新的答案.. –

+1

我不得不讓Swars 2的變種,但除此之外,這完美的作品!謝謝Ashish。 – user3118171