2016-02-07 114 views
2

我試圖讓用戶能夠共享應用的截圖並共享它。我已經獲得了屏幕截圖和分享,但有興趣瞭解是否有人知道如何在截圖時在屏幕截圖的頂部添加一層文本,有點像水印。拍攝截圖並在Swift上添加文字/水印

下面我就截圖:

 let layer = UIApplication.sharedApplication().keyWindow!.layer 
     let scale = UIScreen.mainScreen().scale 
     UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale); 

     layer.renderInContext(UIGraphicsGetCurrentContext()!) 
     let screenshot = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 
     let croppedImage = self.cropImage(screenshot) 
     let activityViewController = UIActivityViewController(activityItems: [croppedImage], applicationActivities: nil) 
     self.presentViewController(activityViewController, animated: true, completion: nil) 

我裁剪屏幕顯示圖像在此功能,所以它只是顯示屏幕的中間:

func cropImage(screenshot: UIImage) -> UIImage { 
    let scale = screenshot.scale 
    let imgSize = screenshot.size 
    let screenHeight = UIScreen.mainScreen().bounds.height 
    let bound = self.view.bounds.height 
    let navHeight = self.navigationController!.navigationBar.frame.height 
    let bottomBarHeight = screenHeight - navHeight - bound 
    let crop = CGRectMake(0, 200, //"start" at the upper-left corner 
     (imgSize.width - 1) * scale, //include half the width of the whole screen 
     (imgSize.height - bottomBarHeight - 300) * scale) //include the height of the navigationBar and the height of view 

    let cgImage = CGImageCreateWithImageInRect(screenshot.CGImage, crop) 
    let image: UIImage = UIImage(CGImage: cgImage!) 
    return image 
} 

回答

2

是的,這是可以做到的那。嘗試添加子視圖到你的圖像視圖如下

let newImageView = UIImageView(image : croppedImage) 
let labelView = UILabel(frame: CGRectMake(30, 30, 100, 20)) //adjust frame to change position of water mark or text 
labelView.text = "my text" 
newImageView.addSubview(labelView) 
UIGraphicsBeginImageContext(newImageView.frame.size) 
newImageView.layer.renderInContext(UIGraphicsGetCurrentContext()!) 
let watermarkedImage = UIGraphicsGetImageFromCurrentImageContext() 
UIGraphicsEndImageContext() 
+0

絕對完美!太棒了,非常感謝你! – kelsheikh