在对 Direct2D 一次仅组合两个几何图形的能力感到失望之后,我决定着手创建一种组合多个几何图形的模块化方法。
由于 Direct2D 确实提供了“CombineWithGeometry”函数,因此该函数仅管理该函数以及临时资源,以创建最终的几何图形。
一些注意事项:此函数相当昂贵,因此不应在帧渲染期间运行它,而应在可能的情况下运行,并且应缓存结果。该版本仅支持路径几何体,但是,添加对其他几何体的支持很容易,只需更改参数中的几何体类型即可。
话不多说,函数如下:
ID2D1PathGeometry* combine_multiple_path_geometries(ID2D1Factory*& srcfactory, int geo_count, ID2D1PathGeometry* geos[]) {
ID2D1PathGeometry* path_geo_1 = NULL;
ID2D1PathGeometry* path_geo_2 = NULL;
srcfactory->CreatePathGeometry(&path_geo_1);
srcfactory->CreatePathGeometry(&path_geo_2);
for (short i = 0; i < geo_count; i++) {
ID2D1GeometrySink* cmpl_s1 = NULL;
ID2D1GeometrySink* cmpl_s2 = NULL;
if (i % 2 == 0) {
//copying into 1
path_geo_1->Open(&cmpl_s1);
if (i == 0)
geos[i]->CombineWithGeometry(geos[i], D2D1_COMBINE_MODE_UNION, NULL, cmpl_s1);
else
geos[i]->CombineWithGeometry(path_geo_2, D2D1_COMBINE_MODE_UNION, NULL, NULL, cmpl_s1);
cmpl_s1->Close();
cmpl_s1->Release();
if (i != 0) {
path_geo_2->Release();
srcfactory->CreatePathGeometry(&path_geo_2);
}
//cmpl_g1 now contains the geometry so far
}
else {
//copying into 2
path_geo_2->Open(&cmpl_s2);
geos[i]->CombineWithGeometry(path_geo_1, D2D1_COMBINE_MODE_UNION, NULL, cmpl_s2);
cmpl_s2->Close();
cmpl_s2->Release();
path_geo_1->Release();
srcfactory->CreatePathGeometry(&path_geo_1);
//cmpl_g2 now contains the geometry so far
}
}
if (geo_count % 2 == 0) {
if (path_geo_1)
path_geo_1->Release();
return path_geo_2;
}
else {
if (path_geo_2)
path_geo_2->Release();
return path_geo_1;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将其包装到一个类中,将其保留为独立的,或者您认为合适的方式。如前所述,您可以轻松支持不同的几何类型,甚至只需稍加调整即可支持多种几何类型。此外,您只需将 D2D1_COMBINE_MODE_UNION 更改为您需要的任何内容即可轻松更改联合模式。
MSDN - Direct2D 几何组合模式:https://msdn.microsoft.com/en-us/library/windows/desktop/dd368083%28v=vs.85%29.aspx
MSDN - Direct2D 几何:https://msdn.microsoft.com/en-us/library/windows/desktop/dd756653%28v=vs.85%29.aspx
MSDN - Direct2D 几何组合:https://msdn.microsoft.com/en-us/library/windows/desktop/dd756676%28v=vs.85%29.aspx