1. 程式人生 > >Swift 給圖片新增水印

Swift 給圖片新增水印

要給圖片新增一個水印感性的想想其實就是在圖片上面繪製文字,一般有如下幾步:第一要獲取到畫布;第二要在畫布中繪製文字;第三獲取到新的圖片。不囉嗦了看程式碼具體和註釋
這裡我是給UIImage這個類添加了一個拓展

import Foundation
import UIKit
extension UIImage {
    func drawTextInImage()->UIImage {
        //開啟圖片上下文
        UIGraphicsBeginImageContext(self.size)
        //圖形重繪
        self.drawInRect(CGRectMake(0
,0,self.size.width,self.size.height)) //水印文字屬性 let att = [NSForegroundColorAttributeName:UIColor.redColor(),NSFontAttributeName:UIFont.systemFontOfSize(50),NSBackgroundColorAttributeName:UIColor.clearColor()] //水印文字大小 let text = NSString(string: "句芒水印製作") let size = text
.sizeWithAttributes(att) //繪製文字 text.drawInRect(CGRectMake(40,60, size.width, size.height), withAttributes: att) //從當前上下文獲取圖片 let image = UIGraphicsGetImageFromCurrentImageContext() //關閉上下文 UIGraphicsEndImageContext() return image } }