所謂的截屏,無非就是把layer渲染到圖形上下文,再從圖形上下文取出來,我已經把它寫在UIView的類目中,具體實現如下:
.h文件
#import <UIKit/UIKit.h>
@interface UIView (UIViewCategory)
- (UIImage *)imageByRenderingView;
- (void)shake;
@end
.m文件
#import "UIView+UIViewCategory.h"
@implementation UIView (UIViewCategory)
//把自身layer畫成一張圖片(截屏)
- (UIImage *)imageByRenderingView
{
//保存當前頁面的alpha值
CGFloat oldAlpha = self.alpha;
//將當前頁面的alpha值設爲1,保證當前頁面處於非透明狀態
self.alpha = 1;
//創建一個基於位圖的上下文(context),並把它push到上下文棧頂,將其設置爲當前上下文
UIGraphicsBeginImageContext(self.bounds.size);
//把當前的整個畫面導入到context中,然後通過context輸出UIImage,這樣就可以把整個屏幕轉化爲圖片
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
//把當前context的內容輸出成一個UIImage圖片
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
//上下文棧pop出創建的context
UIGraphicsEndImageContext();
//把當前頁面畫成圖片之後,就可以把當前頁面的alpha值還原了
self.alpha = oldAlpha;
//把畫出來的圖片返回出去
return resultingImage;
}
//窗口晃動
- (void)shake
{
CAKeyframeAnimation *shakeAnim = [CAKeyframeAnimation animation];
shakeAnim.keyPath = @"transform.translation.x";
CGFloat margin = 10;
shakeAnim.values = @[@0, @(-margin), @(margin), @0];
shakeAnim.duration = 0.2;
shakeAnim.repeatCount = 2;
[self.layer addAnimation:shakeAnim forKey:nil];
}
@end
順便把UIView的抖動效果也加了進來,隨便看看吧!