想要將視圖 (view)上的內容儲存成影像,可以怎麼做呢?因為我想要將相片和邊框結合在一起,然後輸出成影像來儲存。
原以為實作上相當複雜,看了前人的解答之後,原來有API可以直接使用,只要幾行code即可做到!
// 直接在該view controller實作並使用
- (UIImage *)renderToImage
{
// IMPORTANT: using weak link on UIKit
if(UIGraphicsBeginImageContextWithOptions != NULL)
{
UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0.0);
} else {
UIGraphicsBeginImageContext(self.frame.size);
}
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
// 在共用的view controller實作,可以給任何view controller使用
// iOS 4 以後可直接這麼使用
+ (UIImage *)renderToImage:(UIView *)view
{// 將螢幕畫面轉換成影像
UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, [UIScreen mainScreen].scale);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
將畫布設定為想要的大小、是否透明、螢幕尺度即可。
接著只要將回傳的image再做利用即可!至於詳細的參數細節就去看StackOverFlow裡高手的解釋吧~

Comments on: "[iOS] 儲存視圖為影像 (Save View to Image)" (2)
今日製作倉位分享圖用到囉!
讚讚
[…] 如果同時是個程式設計師,這一切就可以交由程式碼來幫我解決囉!可以先回顧文章:儲存視圖為影像 (Save View to Image)。 […]
讚讚