前幾天替一個外掛寫了截屏功能,過程可說是一波三折,今天總算把問題收乾淨。索性把除錯過程中試過的所有截屏做法一次列出來,順便標明各自的限制。
從 iOS 3 時代就在用的老方法,於 iOS 7 被正式廢棄。它屬於私有介面,但效率相當出色。
#importextern "C" CGImageRef UIGetScreenImage(); UIImage *screenshot(void) NS_DEPRECATED_IOS(3_0,7_0); UIImage *screenshot(){ UIImage *image = [UIImage imageWithCGImage:UIGetScreenImage()]; return image; }
網路上最常見的寫法,缺點是解析度停留在非 Retina 的舊標準。
UIImage *screenshot(UIView *);
UIImage *screenshot(UIView *view){
UIGraphicsBeginImageContext(view.frame.size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}從 iPhone 4、iPod Touch 4 起,蘋果開始採用 Retina 螢幕,iOS 4 SDK 相應提供了新介面,第二種寫法於是演進成:
UIImage *screenshot(UIView *) NS_AVAILABLE_IOS(4_0);
UIImage *screenshot(UIView *view){
if(UIGraphicsBeginImageContextWithOptions != NULL)
{
UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0.0);
}
else
{
UIGraphicsBeginImageContext(view.frame.size);
}
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}傳入 0.0 作為 scale,等於讓系統自動採用螢幕原生倍率。
如果你 Hook 的是某個按鈕的點擊方法,第三種寫法就會卡住——手邊根本沒有 view 可以傳。為此 iOS 7 補上了 UIScreen 的相關介面:
UIImage *screenshot(void) NS_AVAILABLE_IOS(7_0);
UIImage *screenshot(){
UIView *view = [[UIScreen mainScreen] snapshotViewAfterScreenUpdates:YES];
if(UIGraphicsBeginImageContextWithOptions != NULL)
{
UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0.0);
}
else
{
UIGraphicsBeginImageContext(view.frame.size);
}
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}@interface SBScreenShotter : NSObject + (id)sharedInstance; - (void)saveScreenshot:(_Bool)arg1; @end
接著直接呼叫:
[[SBScreenShotter sharedInstance] saveScreenshot:YES];
一道白光閃過,等於模擬了使用者按下電源加 Home 鍵的行為。這招在「只需要截一張圖」時很好用,但若想做螢幕錄影(本質上就是不斷截圖),畫面會閃得讓人睜不開眼。更關鍵的是,你拿不到 UIImage 實例,也就無法把它們拼成影片;就算另外 Hook 別的類別取得實例,這個私有介面的效率大概也達不到 30 FPS 的錄影需求。
於是問題回到原點:私有 API 通常效率與品質都勝過公開介面,可惜它在 iOS 7 之後已被廢除。還有別的辦法嗎?有的——改用 Private Framework,直接從底層取螢幕的緩衝數據,再自行組出 UIImage。
#import#import #import #import "IOMobileFramebufferConnection.h" extern "C" IOReturn IOSurfaceLock(IOSurfaceRef buffer, uint32_t options, uint32_t *seed); extern "C" IOReturn IOSurfaceUnlock(IOSurfaceRef buffer, uint32_t options, uint32_t *seed); extern "C" size_t IOSurfaceGetWidth(IOSurfaceRef buffer); extern "C" size_t IOSurfaceGetHeight(IOSurfaceRef buffer); extern "C" IOSurfaceRef IOSurfaceCreate(CFDictionaryRef properties); extern "C" void *IOSurfaceGetBaseAddress(IOSurfaceRef buffer); extern "C" size_t IOSurfaceGetBytesPerRow(IOSurfaceRef buffer); extern const CFStringRef kIOSurfaceAllocSize; extern const CFStringRef kIOSurfaceWidth; extern const CFStringRef kIOSurfaceHeight; extern const CFStringRef kIOSurfaceIsGlobal; extern const CFStringRef kIOSurfaceBytesPerRow; extern const CFStringRef kIOSurfaceBytesPerElement; extern const CFStringRef kIOSurfacePixelFormat; enum { kIOSurfaceLockReadOnly = 0x00000001, kIOSurfaceLockAvoidSync = 0x00000002 }; UIImage *screenshot(void); UIImage *screenshot(){ IOMobileFramebufferConnection connect; kern_return_t result; CoreSurfaceBufferRef screenSurface = NULL; io_service_t framebufferService = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("AppleH1CLCD")); if(!framebufferService) framebufferService = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("AppleM2CLCD")); if(!framebufferService) framebufferService = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("AppleCLCD")); result = IOMobileFramebufferOpen(framebufferService, mach_task_self(), 0, &connect); result = IOMobileFramebufferGetLayerDefaultSurface(connect, 0, &screenSurface); uint32_t aseed; IOSurfaceLock((IOSurfaceRef)screenSurface, 0x00000001, &aseed); size_t width = IOSurfaceGetWidth((IOSurfaceRef)screenSurface); size_t height = IOSurfaceGetHeight((IOSurfaceRef)screenSurface); size_t pitch = width * 4, size = width * height * 4; int bPE = 4; char pixelFormat[4] = {'A','R','G','B'}; CFMutableDictionaryRef dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionarySetValue(dict, kIOSurfaceIsGlobal, kCFBooleanTrue); CFDictionarySetValue(dict, kIOSurfaceBytesPerRow, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &pitch)); CFDictionarySetValue(dict, kIOSurfaceBytesPerElement, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &bPE)); CFDictionarySetValue(dict, kIOSurfaceWidth, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &width)); CFDictionarySetValue(dict, kIOSurfaceHeight, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &height)); CFDictionarySetValue(dict, kIOSurfacePixelFormat, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, pixelFormat)); CFDictionarySetValue(dict, kIOSurfaceAllocSize, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &size)); IOSurfaceRef destSurf = IOSurfaceCreate(dict); IOSurfaceAcceleratorRef outAcc; IOSurfaceAcceleratorCreate(NULL, 0, &outAcc); IOSurfaceAcceleratorTransferSurface(outAcc, (IOSurfaceRef)screenSurface, destSurf, dict, NULL); IOSurfaceUnlock((IOSurfaceRef)screenSurface, kIOSurfaceLockReadOnly, &aseed); CFRelease(outAcc); CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, IOSurfaceGetBaseAddress(destSurf), (width * height * 4), NULL); CGImageRef cgImage = CGImageCreate(width, height, 8, 8*4, IOSurfaceGetBytesPerRow(destSurf), CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little, provider, NULL, YES, kCGRenderingIntentDefault); UIImage *image = [UIImage imageWithCGImage:cgImage]; return image; }
實作這一段時有一個容易忽略的細節:IOMobileFramebuffer 的頭檔需要自行修正。
typedef void * IOMobileFramebufferConnection;
原因是官方反向工程出的頭檔裡,IOMobileFramebufferConnection 被 typedef 成 io_connect_t,一路展開下去是 unsigned int。這在 32 位元環境下剛好與指標同寬,但放到 64 位元就會出問題。相關討論可參考 Stack Overflow:
In the reversed header, IOMobileFramebufferConnection is typedef'd to io_connect_t, which is typedef'd to io_object_t, which is mach_port_t, which is __darwin_mach_port_t, which is __darwin_mach_port_name_t, which is __darwin_natural_t, which is unsigned int! Int just happens to be pointer-sized on 32-bit, but is not under 64-bit. ——StackoverFlow
修改後的頭檔放進專案根目錄即可。若使用 theos,記得在 Makefile 中補上:
YOUR_TWEAK_NAME_PRIVATE_FRAMEWORKS = IOSurface IOKit IOMobileFramebuffer YOUR_TWEAK_NAME_CFLAGS = -I./headers/ -I./headers/IOSurface
若使用 Xcode 上的 Logos Tweak,則在 Build Settings → Search Paths → Header Search Paths 中加入 $(PROJECT_DIR)/YOUR_PROJECT_NAME/headers,搜尋方式設為 recursive;接著在 Build Phases 裡把 IOSurface、IOKit、IOMobileFramebuffer 這三個私有 Framework 連結進來。