1.屏幕截圖
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
? ? ? ? // 1. 創建一個與控制器view一樣大的圖形上下文
? ? ? ? UIGraphicsBeginImageContextWithOptions(self.view.frame.size, NO, 0.0);
? ? ? ? // 1.1 獲取當前上下文
? ? ? ? CGContextRef ctx = UIGraphicsGetCurrentContext();
? ? ? ? // 2. 把控制器的view中的內容渲染到上下文中
? ? ? ? [self.view.layer renderInContext:ctx];
? ? ? ? // 3. 從上下文中獲取圖片
? ? ? ? UIImage* img = UIGraphicsGetImageFromCurrentImageContext();
? ? ? ? // 4. 關閉上下文
? ? ? ? UIGraphicsEndImageContext();
? ? ? ? // 5. 把屏幕截圖保存到相冊
? ? ? ? UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil);
? ? });
2.圖片加水印
? ?// 1. 加載原圖
? ? UIImage* img = [UIImage imageNamed:@"imageName"];
? ? // 2. 根據原圖的大小, 創建一個Bitmap的圖形上下文
? ? UIGraphicsBeginImageContextWithOptions(img.size, NO, 0.0);
? ? // 3. 把原圖繪制到上下文中
? ? [img drawAtPoint:CGPointZero];
? ? // 4. 繪制水印(水印文字、水印圖片)
? ? // 4.1 繪制水印文字
? ? NSString* strMsg = @"水印文字";
? ? NSDictionary* attrs = @{
? ? ? ? NSFontAttributeName : [UIFont systemFontOfSize:25],
? ? ? ? NSForegroundColorAttributeName : [UIColor redColor]
? ? };
? ? [strMsg drawAtPoint:CGPointMake(30, 30) withAttributes:attrs];
? ? // 4.2 繪制圖片水印
? ? // 4.2.1 加載水印圖片
? ? UIImage* imgWatermark = [UIImage imageNamed:@"logo"];
? ? CGFloat margin = 20;
? ? CGFloat w = 200;
? ? CGFloat h = 80;
? ? CGFloat x = img.size.width - w - margin;
? ? CGFloat y = img.size.height - h - margin;
? ? [imgWatermark drawInRect:CGRectMake(x, y, w, h)];
? ? // 5. 從上下文中取出繪制好的圖片
? ? UIImage* imgFinal = UIGraphicsGetImageFromCurrentImageContext();
? ? // 6. 關閉上下文
? ? UIGraphicsEndImageContext();
? ? // 7. 保存圖片
? ? UIImageWriteToSavedPhotosAlbum(imgFinal, nil, nil, nil);