#warning 使用UIWindow category(扩展类)创建本类
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#define UIEventSubtypeMotionShakeNotification @"UIEventSubtypeMotionShakeNotification"
@interface UIWindow (Motion)
- (BOOL)canBecomeFirstResponder;
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event;
@end
#import "UIWindow+Motion.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AssetsLibrary/AssetsLibrary.h>
@implementation UIWindow (Motion)
- (BOOL)canBecomeFirstResponder {//默认是NO,所以得重写此方法,设成YES
return YES;
}
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
NSLog(@"开始摇一摇");
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
AudioServicesPlaySystemSound(1007);
// 方法1
// [self saveImage:[self captureImageFromView:self]];
// 方法二
UIImageWriteToSavedPhotosAlbum([self captureImageFromView:self], self, nil , nil ) ;
NSLog(@"摇一摇结束");
}
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event {
NSLog(@"摇一摇取消");
}
// 保存图片到相册功能
- (void)saveImage:(UIImage*)image {
ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc]init];
[assetsLibrary writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)image.imageOrientation completionBlock:^(NSURL *assetURL, NSError *error) {
if (error) {
NSLog(@"保存失败:%@",error);
}else{
NSLog(@"保存成功");
}
}];
}
//截屏
-(UIImage *)captureImageFromView:(UIView *)view {
CGRect screenRect = [view bounds];
UIGraphicsBeginImageContext(screenRect.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[view.layer renderInContext:ctx];
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
@end