iOS 任意页面摇一摇并截屏保存到相册

本文介绍如何在iOS应用中实现摇一摇功能,并详细解释了如何通过UIWindow扩展类来监听摇动事件,播放震动反馈及保存截图到相册的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值