iOS代码模拟Home+power键实现截屏

2021-01-14  本文已影响0人  啸狼天

导入 #import <AudioToolbox/AudioToolbox.h>

截屏代码如下:

-(void)saveScreen{
    
    [self playSound];
    CGSize imageSize = [[UIScreen mainScreen] bounds].size;
    
    if (NULL != &UIGraphicsBeginImageContextWithOptions) {
        UIGraphicsBeginImageContextWithOptions(imageSize,NO, 0);
    }else{
        UIGraphicsBeginImageContext(imageSize);
    }
    
    CGContextRef context =UIGraphicsGetCurrentContext();
    for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
        
        if (![window respondsToSelector:@selector(screen)] || [windowscreen] == [UIScreen mainScreen]) {
            
            CGContextSaveGState(context);
            CGContextTranslateCTM(context, [windowcenter].x, [windowcenter].y);
            CGContextConcatCTM(context, [windowtransform]);
            CGContextTranslateCTM(context, -[windowbounds].size.width*[[windowlayer] anchorPoint].x, -[windowbounds].size.height*[[windowlayer] anchorPoint].y);
            [[window layer] renderInContext:context];
            CGContextRestoreGState(context);
        }
    }
    
    UIImage *image =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageWriteToSavedPhotosAlbum(image,self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:),nil);
}

- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    
    if (!error) {
        _HUD.labelText =@"保存成功";
        _time=1;
    }else{
        _HUD.labelText =@"保存失败";
        _time=0;
    }
    [_HUD hide:YESafterDelay:1.0];
}


// 模拟播放快门声音加白光
-(void) playSound{
    UIView * view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    view.backgroundColor = [UIColor whiteColor];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:view];
    AudioServicesPlaySystemSound(shake_sound_male_id);
    
    [UIView animateWithDuration:0.5 animations:^{
        view.alpha = 0.05;
    } completion:^(BOOL finished) {
        [view removeFromSuperview];
    }];
}

快门声ID如下:
static SystemSoundID shake_sound_male_id = 1108;

使用如下方法播放系统声音的ID
AudioServicesPlaySystemSound(shake_sound_male_id);

具体ID连接如下

http://iphonedevwiki.net/index.php/AudioServices

上一篇下一篇

猜你喜欢

热点阅读