基于C++进行图层标注时,我们只需设置文字样式(字体、字号、颜色、是否加粗、是否斜体、是否下划线、是否删除线)、要标注的字段、是否显示标注即可。
设置文字样式的代码如下:
ITextSymbolPtr Common::GetTextSymbol(double dSize, int nR, int nG, int nB, const CString sFont = _T("宋体"), BOOL bBold = FALSE, BOOL bItalic = FALSE, BOOL bUnderline = FALSE, BOOL bStrikethrough = FALSE)
{
if (0 >= dSize || 0 > nR || nR>255 || 0 > nG || nG > 255 || 0 > nB || nB > 255) return nullptr;
IFontPtr ipFont(CLSID_StdFont);
if (nullptr == ipFont) return nullptr;
HRESULT hr = ipFont->put_Name(CComBSTR(sFont));
if (FAILED(hr)) return nullptr;
hr = ipFont->put_Bold(bBold);
hr = ipFont->put_Italic(bItalic);
hr = ipFont->put_Underline(bUnderline);
hr = ipFont->put_Strikethrough(bStrikethrough);
IColorPtr ipColor(CLSID_RgbColor);
if (nullptr == ipColor) return nullptr;
hr = ipColor->put_esriRGB((OLE_COLOR)RGB(nR, nG, nB));
if (FAILED(hr)) return nullptr;
IFontDispPtr ipFontDisp = ipFont;
if (nullptr == ipFontDisp) return nullptr;
ITextSymbolPtr ipTextSymbol(CLSID_TextSymbol);
if (nullptr == ipTextSymbol) return nullptr;
hr = ipTextSymbol->put_Font(ipFontDisp);
if (FAILED(hr)) return nullptr;
hr = ipTextSymbol->put_Color(ipColor);
if (FAILED(hr)) return nullptr;
hr = ipTextSymbol->put_Size(dSize);
if (FAILED(hr)) return nullptr;
return ipTextSymbol;
}
对一个要素图层实现简单标注的代码如下:
IGeoFeatureLayerPtr ipGeoFeatureLayer = (IGeoFeatureLayerPtr)ipFeatureLayer;
IAnnotateLayerPropertiesCollectionPtr ipAnnotateLayerPropertiesCollection = nullptr;
hr = ipGeoFeatureLayer->get_AnnotationProperties(&ipAnnotateLayerPropertiesCollection);
IAnnotateLayerPropertiesPtr ipAnnotateLayerProperties = nullptr;
long lCount = -1;
hr = ipAnnotateLayerPropertiesCollection->get_Count(&lCount);
if (FAILED(hr) || 0 >= lCount) continue;
hr = ipAnnotateLayerPropertiesCollection->QueryItem(0, &ipAnnotateLayerProperties, NULL, NULL);
if (FAILED(hr) || nullptr == ipAnnotateLayerProperties) continue;
ILabelEngineLayerProperties2Ptr ipEngine = ipAnnotateLayerProperties;
hr = ipEngine->putref_Symbol(Common::GetTextSymbol(10, 0, 255, 0, _T("微软雅黑"), TRUE, TRUE, TRUE, TRUE));
hr = ipEngine->put_Expression(_bstr_t("[OBJECTID]"));
hr = ipAnnotateLayerPropertiesCollection->Clear();
hr = ipAnnotateLayerPropertiesCollection->Add((IAnnotateLayerPropertiesPtr)ipEngine);
hr = ipGeoFeatureLayer->put_AnnotationProperties(ipAnnotateLayerPropertiesCollection);
hr = ipGeoFeatureLayer->put_DisplayAnnotation(VARIANT_TRUE);
可以看出,本质上,我们将IFeatureLayer转为IGeoFeatureLayer后,取到其标注属性对象即AnnotateLayerPropertiesCollection后,在LabelEngineLayerProperties中设置标注样式,再赋给图层,并进行显示即可。
当然,还可以进行更复杂的标注设置,如标注显示的比例尺范围、冲突策略等。本文不赘述。