您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 偵測使用者截圖並取得截圖內容

編輯:iOS 開發綜合

微信有個很貼心的設計:它能察覺使用者剛剛做了截圖(Home + Power),稍後點擊附加功能時,會主動詢問是否要發送那張圖片。這個互動體驗很好,於是就來研究該怎麼實現。

iOS 7 前後的差別

在 iOS 7 之前,使用者一旦截圖,系統會自動取消螢幕上所有的 touch 事件,觸發 touchesCancelled:withEvent:。因此只要偵測這個方法的呼叫,再去讀取相簿中最新的照片並判斷是否為截圖,就能達到目的。

但 iOS 7 之後,截圖不再取消 touch 事件,這直接讓 Snapchat、Facebook Poke 這類依賴該行為的應用在 iOS 7 剛問世時失效。

若不另尋他法,也可以讓 App 啟動後在背景輪詢相簿最新一張照片,比對是否符合截圖特徵。這條路走得通,但顯得笨重:一方面必須取得使用者相簿權限,另一方面持續輪詢會消耗更多系統資源。

好在蘋果雖然收緊了部分行為,也相應開放了替代方案。

改用官方通知

iOS 7 提供了全新的通知:UIApplicationUserDidTakeScreenshotNotification,和往常一樣訂閱即可得知截圖時機。

要注意的是,這個通知是在截圖完成之後才送出的,目前無法在截圖發生「之前」取得通知。

當時就期待蘋果能在後續版本補上 UIApplicationUserWillTakeScreenshotNotification —— 只有 did 沒有 will,實在不像是蘋果的風格。

實作:註冊通知

// 註冊通知
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(userDidTakeScreenshot:)
                                             name:UIApplicationUserDidTakeScreenshotNotification
                                           object:nil];

實作:監聽截圖

// 截圖響應
- (void)userDidTakeScreenshot:(NSNotification *)notification {
    NSLog(@"檢測到截屏");

    // 取得截圖
    UIImage *image_ = [self imageWithScreenshot];

    // 顯示出來
    UIImageView *imgvPhoto = [[UIImageView alloc] initWithImage:image_];
    imgvPhoto.frame = CGRectMake(self.window.frame.size.width / 2,
                                 self.window.frame.size.height / 2,
                                 self.window.frame.size.width / 2,
                                 self.window.frame.size.height / 2);

    // 白色邊框
    CALayer *layer = [imgvPhoto layer];
    layer.borderColor = [[UIColor whiteColor] CGColor];
    layer.borderWidth = 5.0f;

    // 四周陰影
    imgvPhoto.layer.shadowColor = [UIColor blackColor].CGColor;
    imgvPhoto.layer.shadowOffset = CGSizeMake(0, 0);
    imgvPhoto.layer.shadowOpacity = 0.5;
    imgvPhoto.layer.shadowRadius = 10.0;

    // 兩側陰影
    imgvPhoto.layer.shadowColor = [UIColor blackColor].CGColor;
    imgvPhoto.layer.shadowOffset = CGSizeMake(4, 4);
    imgvPhoto.layer.shadowOpacity = 0.5;
    imgvPhoto.layer.shadowRadius = 2.0;

    [self.window addSubview:imgvPhoto];
}

這個方法一共做了三件事:印出偵測日誌、取得截圖、以螢幕四分之一的大小顯示在右下角,並加上白色邊框與陰影加以突出。

實作:取得截圖圖片

/**
 * 截取當前畫面,回傳 PNG 格式的 NSData
 */
- (NSData *)dataWithScreenshotInPNGFormat {
    CGSize imageSize = CGSizeZero;
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;

    if (UIInterfaceOrientationIsPortrait(orientation)) {
        imageSize = [UIScreen mainScreen].bounds.size;
    } else {
        imageSize = CGSizeMake([UIScreen mainScreen].bounds.size.height,
                               [UIScreen mainScreen].bounds.size.width);
    }

    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();

    for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
        CGContextSaveGState(context);
        CGContextTranslateCTM(context, window.center.x, window.center.y);
        CGContextConcatCTM(context, window.transform);
        CGContextTranslateCTM(context,
                              -window.bounds.size.width * window.layer.anchorPoint.x,
                              -window.bounds.size.height * window.layer.anchorPoint.y);

        if (orientation == UIInterfaceOrientationLandscapeLeft) {
            CGContextRotateCTM(context, M_PI_2);
            CGContextTranslateCTM(context, 0, -imageSize.width);
        } else if (orientation == UIInterfaceOrientationLandscapeRight) {
            CGContextRotateCTM(context, -M_PI_2);
            CGContextTranslateCTM(context, -imageSize.height, 0);
        } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
            CGContextRotateCTM(context, M_PI);
            CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
        }

        if ([window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
            [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
        } else {
            [window.layer renderInContext:context];
        }
        CGContextRestoreGState(context);
    }

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return UIImagePNGRepresentation(image);
}

/**
 * 回傳截圖
 */
- (UIImage *)imageWithScreenshot {
    NSData *imageData = [self dataWithScreenshotInPNGFormat];
    return [UIImage imageWithData:imageData];
}

這裡刻意逐一走訪所有 UIWindow,並依當前的 statusBarOrientation 做座標系旋轉處理,才能把橫向、倒置等狀態都正確渲染出來。若使用較新的系統,也可以直接用 UIScreen 的 snapshot 相關 API 取代手繪流程,程式碼會短很多。

最後提醒:這段偵測邏輯必須在真機上測試,因為截圖行為(Home + Power)在模擬器上難以觸發。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved