private void AddLabel(IFeatureLayer pLayer,string fieldname,ITextSymbol Symbol)
{ container.DeleteAllElements(); IFeatureClass pClass = pLayer.FeatureClass;
IFields pFields = pClass.Fields;
int index = pFields.FindField(fieldname); ITextElement pTextElement;
IEnvelope pEnv = null;
IElement pElement = null;
//pTextElement.ScaleText = true;
//pTextElement.Symbol = Symbol; IFeatureCursor pCursor = pClass.Search(null, false);
IFeature pFeature;
IPoint point;
pFeature = pCursor.NextFeature();
while (pFeature != null)
{
pEnv = pFeature.Extent;
point = new PointClass();
point.PutCoords((pEnv.XMin + pEnv.XMax) * 0.5, (pEnv.YMax + pEnv.YMin) * 0.5); pTextElement = new TextElementClass();
pTextElement.Symbol = Symbol;
pTextElement.ScaleText = true;
pTextElement.Text = pFeature.get_Value(index).ToString(); pElement = pTextElement as IElement;
pElement.Geometry = point; container.AddElement(pElement, 0);
pFeature = pCursor.NextFeature();
}
axMapControl1.Refresh();
}
以上为第一种方法,另一种方法(利用提供的接口):
private void Label(IFeatureLayer pLayer, string fieldname, ITextSymbol Symbol)
{
IGeoFeatureLayer pGeoFeaturelayer = pLayer as IGeoFeatureLayer;
IAnnotateLayerPropertiesCollection annotLayercol = pGeoFeaturelayer.AnnotationProperties;
annotLayercol.Clear(); IBasicOverposterLayerProperties basicoverPost = new BasicOverposterLayerPropertiesClass();
basicoverPost.BufferRatio = 0.2;
switch (pLayer.FeatureClass.ShapeType)
{
case ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolygon:
basicoverPost.FeatureType = esriBasicOverposterFeatureType.esriOverposterPolygon;
break;
case ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline:
basicoverPost.FeatureType = esriBasicOverposterFeatureType.esriOverposterPolyline;
break;
case ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint:
basicoverPost.FeatureType = esriBasicOverposterFeatureType.esriOverposterPoint;
break; }
ILabelEngineLayerProperties pLabelEngine = new LabelEngineLayerPropertiesClass();
pLabelEngine.Expression = "[" + fieldname + "]";
pLabelEngine.Symbol = Symbol;
pLabelEngine.BasicOverposterLayerProperties = basicoverPost; annotLayercol.Add((IAnnotateLayerProperties)pLabelEngine);
pGeoFeaturelayer.DisplayAnnotation = true;
axMapControl1.Refresh();
}
最后调用:
private void labelFeatureToolStripMenuItem_Click(object sender, EventArgs e)
{
//MessageBox.Show(PropertiesForm.FieldName);
IFeatureLayer layer = axMapControl1.CustomProperty as IFeatureLayer; IGeoFeatureLayer pGeoFeaturelayer = layer as IGeoFeatureLayer;
IAnnotateLayerPropertiesCollection annotLayercol = pGeoFeaturelayer.AnnotationProperties; string fieldname = PropertiesForm.FieldName;
ITextSymbol symbol = PropertiesForm.TextSymbol; if (show == false)
{ //AddLabel(layer, "XZQMC", symbol);
Label(layer, fieldname, symbol);
show = true;
MessageBox.Show("插入成功!");
} else
{
annotLayercol.Clear();
//container.DeleteAllElements();
show = false; axMapControl1.Refresh();
}
}