https://blog.csdn.net/xpg4321/article/details/112358449 介绍了如何枚举mac系统的窗口。
下面介绍如何截取窗口图像。
1.获取窗口信息
参考前一节介绍的mac枚举窗口函数获取窗口信息。
if(nullptr == _screen_caputre)
break;
bool b = _screen_caputre->caputreWindow(_record_windows, (char *)_buffer, true);
error = b?AE_NO:AE_ERROR;
2.截图
CGImageRef mainimageRef = CGWindowListCreateImage(CGRectNull, kCGWindowListOptionIncludingWindow, _main_record_window.Handle, kCGWindowImageNominalResolution | kCGWindowImageShouldBeOpaque);
依旧使用CGWindowListCreateImage进行截图与截屏类似,只是参数变了,这里需要的是窗口句柄。
3.获取RGB数据
auto width = CGImageGetWidth(mainimageRef);
auto height = CGImageGetHeight(mainimageRef);
auto prov = CGImageGetDataProvider(mainimageRef);
if (!prov)
{
CGImageRelease(mainimageRef);
return false;
}
auto rawdatas = CGDataProviderCopyData(prov);
auto buf = CFDataGetBytePtr(rawdatas);
memcpy(buffer, buf, width*height*4);
CGImageRelease(mainimageRef);
4.完整代码
bool MacScreenCaputre::caputreWindow(const std::string &name, char *buffer, bool needCursor)
{
Window record_window = getWindow(name);
if(0 == record_window.Handle)
return false;
CGImageRef mainimageRef = CGWindowListCreateImage(CGRectNull, kCGWindowListOptionIncludingWindow, record_window.Handle, kCGWindowImageNominalResolution | kCGWindowImageShouldBeOpaque);
auto width = CGImageGetWidth(mainimageRef);
auto height = CGImageGetHeight(mainimageRef);
auto prov = CGImageGetDataProvider(mainimageRef);
if (!prov)
{
CGImageRelease(mainimageRef);
return false;
}
auto rawdatas = CGDataProviderCopyData(prov);
auto buf = CFDataGetBytePtr(rawdatas);
memcpy(buffer, buf, width*height*4);
CGImageRelease(mainimageRef);
return true;
}