Create an IProjectItem from a layout template pagx file and add it to the project
vartemplateFileName="Layout.pagx";// Get layout Template Path from the project's home folder and combine it with a file namevarprojectPath=CoreModule.CurrentProject.HomeFolderPath;varlayoutTemplateFilePath=System.IO.Path.Combine(projectPath,templateFileName);// Create a new layout project item with the layout file path// Create an IProjectItem using a layout template pagx fileIProjectItempagx=ItemFactory.Instance.Create(layoutTemplateFilePath)asIProjectItem;// Add the IProjectItem to the current project//Note: Needs QueuedTask to runProject.Current.AddItem(pagx);
Get a Layout by name from the current project
LayoutProjectItemlayoutItemByName=Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault((lpi)=>lpi.Name=="MyLayout");//Note: Needs QueuedTask to runLayoutlayoutByName=layoutItemByName.GetLayout();
Reference layout project items and their associated layout
//Reference layout project items and their associated layout.//A layout project item is an item that appears in the Layouts//folder in the Catalog pane.//Reference all the layout project itemsIEnumerable<LayoutProjectItem>layoutProjectItems=Project.Current.GetItems<LayoutProjectItem>();//Or reference a specific layout project item by nameLayoutProjectItemspecificLayoutItem=Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item =>item.Name.Equals("MyLayoutItem"));
Open a layout project item in a new view
//Open a layout project item in a new view.//A layout project item may exist but it may not be open in a view. //Reference a layout project item by nameLayoutProjectItemlayoutItemByName=Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item =>item.Name.Equals("MyLayoutItem"));//Get the layout associated with the layout project item//Note: Needs QueuedTask to runLayoutlayoutFromItem=layoutItemByName.GetLayout();//Worker thread//Create the new pane - call on UIILayoutPaneiNewLayoutPane=awaitProApp.Panes.CreateLayoutPaneAsync(layout);//GUI thread
Activate an already open layout view
//Activate an already open layout view.//A layout view may be open but it may not be active.//Find the pane that references the layout and activate it. //Note - there can be multiple panes referencing the same layout.foreach(varpaneinProApp.Panes){varlayoutPane=paneasILayoutPane;if(layoutPane==null)//if not a layout view, continue to the next panecontinue;if(layoutPane.LayoutView.Layout==layout)//activate the view{(layoutPaneasPane).Activate();return;}}
Reference the active layout view
//Reference the active layout view.//Confirm if the current, active view is a layout view.//If it is, do something.LayoutViewactiveLayoutView=LayoutView.Active;if(activeLayoutView!=null){// do something}
Import a pagx into a project
//Create a layout project item from importing a pagx file//Note: Needs QueuedTask to runIProjectItempagx=ItemFactory.Instance.Create(@"C:\Temp\Layout.pagx")asIProjectItem;Project.Current.AddItem(pagx);
Remove a layout project item
//Remove a layout project item.//Remove the layout from the project//Note: Needs QueuedTask to runProject.Current.RemoveItem(layoutItem);
Create a new, basic layout and open it
//Create a new, basic layout and open it.//Create layout with minimum set of parameters on the worker thread//Note: Needs QueuedTask to runvarmyNewLayout=LayoutFactory.Instance.CreateLayout(8.5,11,LinearUnit.Inches);myNewLayout.SetName("New 8.5x11 Layout");//Open new layout on the GUI threadawaitProApp.Panes.CreateLayoutPaneAsync(myNewLayout);
Create a new layout using a modified CIM and open it
//Create a new layout using a modified CIM and open it.//The CIM exposes additional members that may not be//available through the managed API. //In this example, optional guides are added.//Create a new CIMLayout on the worker thread//Note: Needs QueuedTask to run//Set up a CIM pageCIMPagenewPage=newCIMPage{//required parametersWidth=8.5,Height=11,Units=LinearUnit.Inches,//optional rulersShowRulers=true,SmallestRulerDivision=0.5,//optional guidesShowGuides=true};CIMGuideguide1=newCIMGuide{Position=1,Orientation=Orientation.Vertical};CIMGuideguide2=newCIMGuide{Position=6.5,Orientation=Orientation.Vertical};CIMGuideguide3=newCIMGuide{Position=1,Orientation=Orientation.Horizontal};CIMGuideguide4=newCIMGuide{Position=10,Orientation=Orientation.Horizontal};List<CIMGuide>guideList=newList<CIMGuide>{guide1,guide2,guide3,guide4};newPage.Guides=guideList.ToArray();//Construct the new layout using the customized cim definitionsvarlayout_local=LayoutFactory.Instance.CreateLayout(newPage);layout_local.SetName("New 8.5x11 Layout");//Open new layout on the GUI threadawaitProApp.Panes.CreateLayoutPaneAsync(layout_local);
Change the layout page size
//Change the layout page size.//Reference the layout project itemLayoutProjectItemlytItem=Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item =>item.Name.Equals("MyLayoutItem"));if(layoutItem!=null){//Note: Needs QueuedTask to run//Get the layoutLayoutlyt=lytItem.GetLayout();if(lyt!=null){//Change propertiesCIMPagepage=lyt.GetPage();page.Width=8.5;page.Height=11;//Apply the changes to the layoutlyt.SetPage(page);}}
ProSnippet Group CIM Graphics and GraphicFactory
Create Circle Graphic
//Note: Must be on QueuedTask.Run//Build geometryCoordinate2Dcenter=newCoordinate2D(2,4);EllipticArcSegmentcircle_seg=EllipticArcBuilderEx.CreateCircle(newCoordinate2D(2,4),0.5,ArcOrientation.ArcClockwise,null);varcircle_poly=PolygonBuilderEx.CreatePolygon(PolylineBuilderEx.CreatePolyline(circle_seg));//PolylineBuilderEx.CreatePolyline(cir, AttributeFlags.AllAttributes));//Set symbology, create and add element to layoutCIMStrokeoutline=SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB,2.0,SimpleLineStyle.Dash);CIMPolygonSymbolcircleSym=SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB,SimpleFillStyle.Solid,outline);SymbolFactory.Instance.ConstructPolygonSymbol(null,SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.RedRGB,2));varcircleGraphic=GraphicFactory.Instance.CreateSimpleGraphic(circle_poly,circleSym);//Make an element to add to GraphicsLayer or Layout//var elemInfo = new ElementInfo() { Anchor = Anchor.CenterPoint };//GraphicElement cirElm = ElementFactory.Instance.CreateGraphicElement(// layout, circleGraphic, "New Circle", true, elemInfo);
Create Circle Text Graphic
//Note: Must be on QueuedTask.Run//Build geometryCoordinate2Dcenter=newCoordinate2D(4.5,4);vareabCir=newEllipticArcBuilderEx(center,0.5,ArcOrientation.ArcClockwise);varcir=eabCir.ToSegment();varpoly=PolygonBuilderEx.CreatePolygon(PolylineBuilderEx.CreatePolyline(cir,AttributeFlags.AllAttributes));//Set symbology, create and add element to layoutCIMTextSymbolsym=SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.GreenRGB,10,"Arial","Regular");stringtext="Circle, circle, circle";vargraphic=GraphicFactory.Instance.CreateSimpleTextGraphic(TextType.CircleParagraph,poly,sym,text);//Make an element to add to GraphicsLayer or Layout//var ge = ElementFactory.Instance.CreateGraphicElement(layout, graphic,// "New Circle Text", true);
Create Bezier Graphic
//Note: Must be on QueuedTask.Run//Build geometryCoordinate2Dpt1=newCoordinate2D(3.5,7.5);Coordinate2Dpt2=newCoordinate2D(4.16,8);Coordinate2Dpt3=newCoordinate2D(4.83,7.1);Coordinate2Dpt4=newCoordinate2D(5.5,7.5);varbez=newCubicBezierBuilderEx(pt1,pt2,pt3,pt4);varbezSeg=bez.ToSegment();PolylinebezPl=PolylineBuilderEx.CreatePolyline(bezSeg,AttributeFlags.AllAttributes);//Set symbology, create and add element to layoutCIMTextSymbolsym=SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.BlackRGB,24,"Comic Sans MS","Regular");vargraphic=GraphicFactory.Instance.CreateSimpleTextGraphic(TextType.SplinedText,bezPl,sym,"Splined text");//Make an element to add to GraphicsLayer or Layout//var ge = ElementFactory.Instance.CreateGraphicElement(layout, graphic);
Create Legend Patch Graphic
//Note: Must be on QueuedTask.Run//Build geometryList<Coordinate2D>plyCoords=newList<Coordinate2D>();plyCoords.Add(newCoordinate2D(1,1));plyCoords.Add(newCoordinate2D(1.25,2));plyCoords.Add(newCoordinate2D(1.5,1.1));plyCoords.Add(newCoordinate2D(1.75,2));plyCoords.Add(newCoordinate2D(2,1.1));plyCoords.Add(newCoordinate2D(2.25,2));plyCoords.Add(newCoordinate2D(2.5,1.1));plyCoords.Add(newCoordinate2D(2.75,2));plyCoords.Add(newCoordinate2D(3,1));Polygonpoly=PolygonBuilderEx.CreatePolygon(plyCoords);//Set symbology, create and add element to layoutCIMStrokeoutline=SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB,2.0,SimpleLineStyle.Solid);CIMPolygonSymbolpolySym=SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB,SimpleFillStyle.ForwardDiagonal,outline);vargraphic=GraphicFactory.Instance.CreateLegendPatchGraphic(PatchShape.AreaBoundary,poly.Extent,polySym);//Make an element to add to GraphicsLayer or Layout////var elemInfo = new ElementInfo()//{// CustomProperties = null,// Anchor = Anchor.LeftMidPoint//};//var ge = ElementFactory.Instance.CreateGraphicElement(layout, graphic,// "New Legend Patch", true, elemInfo);
Create Arrow Graphic
//Note: Must be on QueuedTask.Run//Build geometryList<Coordinate2D>plCoords=newList<Coordinate2D>();plCoords.Add(newCoordinate2D(1,8.5));plCoords.Add(newCoordinate2D(1.66,9));plCoords.Add(newCoordinate2D(2.33,8.1));plCoords.Add(newCoordinate2D(3,8.5));PolylinelinePl=PolylineBuilderEx.CreatePolyline(plCoords);//Set up the arrow infovararrowInfo=newArrowInfo(){ArrowHeadKey=ArrowInfo.DefaultArrowHeadKeys[1],ArrowOnBothEnds=true,ArrowSizePoints=30,LineWidthPoints=15};vargraphic=GraphicFactory.Instance.CreateArrowGraphic(linePl,arrowInfo);//Make an element to add to GraphicsLayer or Layout//var ge = ElementFactory.Instance.CreateGraphicElement(// layout, graphic, "Arrow Line", false);
Create Picture Graphic
//Note: Must be on QueuedTask.Run//Build geometryCoordinate2Dll=newCoordinate2D(3.5,1);Coordinate2Dur=newCoordinate2D(5.5,2);Envelopeenv=EnvelopeBuilderEx.CreateEnvelope(ll,ur);stringpicPath=System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),"SamplePicture.jpg");//Create and add element to layoutvargraphic=GraphicFactory.Instance.CreatePictureGraphic(env.Center,picPath);//Make an element to add to GraphicsLayer or Layout//var ge = ElementFactory.Instance.CreateGraphicElement(layout, graphic);
Get Graphic Outline
//given a graphic, extract its outline geometryvargraphic_outline=GraphicFactory.Instance.GetGraphicOutline(layout,cimGraphic);//TODO - use the geometry - eg, make another graphicvaroutline_graphic=GraphicFactory.Instance.CreateSimpleGraphic(graphic_outline);//... etc.
Get Graphic Outline from Graphic Element
//given a graphic, extract its outline geometryvargraphic_elem=layout.GetElementsAsFlattenedList().OfType<GraphicElement>()?.FirstOrDefault();if(graphic_elem!=null)//can be point, line, poly, or textreturn;varoutline=GraphicFactory.Instance.GetGraphicOutline(layout,graphic_elem.GetGraphic());//create an element using the outlinevarelem=ElementFactory.Instance.CreateGraphicElement(layout,outline);//... etc.
Create Layout Graphic Elements
Create Ellipse Graphic Element
//Note: Must be on QueuedTask.Run//Build geometryCoordinate2Dcenter=newCoordinate2D(2,2.75);vareabElp=newEllipticArcBuilderEx(center,0,1,0.45,ArcOrientation.ArcClockwise);varellipse=eabElp.ToSegment();//Set symbology, create and add element to layoutCIMStrokeoutline=SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.GreenRGB,2.0,SimpleLineStyle.Dot);CIMPolygonSymbolellipseSym=SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.GreyRGB,SimpleFillStyle.Vertical,outline);varpoly=PolygonBuilderEx.CreatePolygon(PolylineBuilderEx.CreatePolyline(ellipse,AttributeFlags.AllAttributes));varelpElm=ElementFactory.Instance.CreateGraphicElement(layout,poly,ellipseSym,"New Ellipse");
Create Lasso Line, Freehand Graphic Element
//Note: Must be on QueuedTask.Run//Build geometryList<Coordinate2D>plCoords=newList<Coordinate2D>();plCoords.Add(newCoordinate2D(1.5,10.5));plCoords.Add(newCoordinate2D(1.25,9.5));plCoords.Add(newCoordinate2D(1,10.5));plCoords.Add(newCoordinate2D(0.75,9.5));plCoords.Add(newCoordinate2D(0.5,10.5));plCoords.Add(newCoordinate2D(0.5,1));plCoords.Add(newCoordinate2D(0.75,2));plCoords.Add(newCoordinate2D(1,1));PolylinelinePl=PolylineBuilderEx.CreatePolyline(plCoords);//Set symbology, create and add element to layoutCIMLineSymbollineSym=SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlackRGB,2.0,SimpleLineStyle.Solid);//var graphic = GraphicFactory.Instance.CreateShapeGraphic(linePl, lineSym);varge=ElementFactory.Instance.CreateGraphicElement(layout,linePl,lineSym,"New Freehand");
Create Lasso Polygon, Freehand Element
//Note: Must be on QueuedTask.RunList<Coordinate2D>plyCoords=newList<Coordinate2D>();plyCoords.Add(newCoordinate2D(1,1));plyCoords.Add(newCoordinate2D(1.25,2));plyCoords.Add(newCoordinate2D(1.5,1.1));plyCoords.Add(newCoordinate2D(1.75,2));plyCoords.Add(newCoordinate2D(2,1.1));plyCoords.Add(newCoordinate2D(2.25,2));plyCoords.Add(newCoordinate2D(2.5,1.1));plyCoords.Add(newCoordinate2D(2.75,2));plyCoords.Add(newCoordinate2D(3,1));Polygonpoly=PolygonBuilderEx.CreatePolygon(plyCoords);//Set symbology, create and add element to layoutCIMStrokeoutline=SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB,2.0,SimpleLineStyle.Solid);CIMPolygonSymbolpolySym=SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB,SimpleFillStyle.ForwardDiagonal,outline);ElementFactory.Instance.CreateGraphicElement(layout,poly,polySym,"New Lasso");
Create Line Element
//Note: Must be on QueuedTask.Run//Build geometryList<Coordinate2D>plCoords=newList<Coordinate2D>();plCoords.Add(newCoordinate2D(1,8.5));plCoords.Add(newCoordinate2D(1.66,9));plCoords.Add(newCoordinate2D(2.33,8.1));plCoords.Add(newCoordinate2D(3,8.5));PolylinelinePl=PolylineBuilderEx.CreatePolyline(plCoords);//Reference a line symbol in a stylevarProjectStyles=Project.Current.GetItems<StyleProjectItem>();StyleProjectItemstyle=ProjectStyles.First(x =>x.Name=="ArcGIS 2D");varsymStyle=style.SearchSymbols(StyleItemType.LineSymbol,"Line with 2 Markers")[0];CIMLineSymbollineSym=symStyle.SymbolasCIMLineSymbol;lineSym.SetSize(20);//Set symbology, create and add element to layout//CIMLineSymbol lineSym = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlueRGB, 4.0, SimpleLineStyle.Solid);ElementFactory.Instance.CreateGraphicElement(layout,linePl,lineSym,"New Line");
Create Point Element
//Note: Must be on QueuedTask.Run(() => { ...//Build geometryCoordinate2Dcoord2D=newCoordinate2D(2.0,10.0);//Reference a point symbol in a styleStyleProjectItemstylePrjItm=Project.Current.GetItems<StyleProjectItem>().FirstOrDefault(item =>item.Name=="ArcGIS 2D");SymbolStyleItemsymStyleItm=stylePrjItm.SearchSymbols(StyleItemType.PointSymbol,"City Hall")[0];CIMPointSymbolpointSym=symStyleItm.SymbolasCIMPointSymbol;pointSym.SetSize(50);varelemInfo=newElementInfo(){CustomProperties=newList<CIMStringMap>(){newCIMStringMap(){Key="Key1",Value="Value1"},newCIMStringMap(){Key="Key2",Value="Value2"}},Anchor=Anchor.TopRightCorner,Rotation=45.0};vargraphic=GraphicFactory.Instance.CreateSimpleGraphic(coord2D.ToMapPoint(),pointSym);ElementFactory.Instance.CreateGraphicElement(layout,graphic,"New Point",true,elemInfo);
Create Polygon Element
//Note: Must be on QueuedTask.Run//Build geometryList<Coordinate2D>plyCoords=newList<Coordinate2D>();plyCoords.Add(newCoordinate2D(1,7));plyCoords.Add(newCoordinate2D(2,7));plyCoords.Add(newCoordinate2D(2,6.7));plyCoords.Add(newCoordinate2D(3,6.7));plyCoords.Add(newCoordinate2D(3,6.1));plyCoords.Add(newCoordinate2D(1,6.1));Polygonpoly=PolygonBuilderEx.CreatePolygon(plyCoords);//Set symbology, create and add element to layoutCIMStrokeoutline=SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlueRGB,2.0,SimpleLineStyle.DashDotDot);CIMPolygonSymbolpolySym=SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB,SimpleFillStyle.ForwardDiagonal,outline);ElementFactory.Instance.CreateGraphicElement(layout,poly,polySym,"New Polygon",false);
Create Rectangle Element
//Note: Must be on QueuedTask.Run//Build geometryCoordinate2Dll=newCoordinate2D(1.0,4.75);Coordinate2Dur=newCoordinate2D(3.0,5.75);Envelopeenv=EnvelopeBuilderEx.CreateEnvelope(ll,ur);//Set symbology, create and add element to layoutCIMStrokeoutline=SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB,5.0,SimpleLineStyle.Solid);CIMPolygonSymbolpolySym=SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.GreenRGB,SimpleFillStyle.DiagonalCross,outline);varge=GraphicFactory.Instance.CreateSimpleGraphic(env,polySym);varelemInfo=newElementInfo(){Anchor=Anchor.CenterPoint,Rotation=45.0,CornerRounding=5.0};ElementFactory.Instance.CreateGraphicElement(layout,env,polySym,"New Rectangle",false,elemInfo);
Create Bezier Curve Element
//Note: Must be on QueuedTask.Run//Build geometryCoordinate2Dpt1=newCoordinate2D(1,7.5);Coordinate2Dpt2=newCoordinate2D(1.66,8);Coordinate2Dpt3=newCoordinate2D(2.33,7.1);Coordinate2Dpt4=newCoordinate2D(3,7.5);varbez=newCubicBezierBuilderEx(pt1,pt2,pt3,pt4);varbezSeg=bez.ToSegment();PolylinebezPl=PolylineBuilderEx.CreatePolyline(bezSeg,AttributeFlags.AllAttributes);//Set symbology, create and add element to layoutCIMLineSymbollineSym=SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.RedRGB,4.0,SimpleLineStyle.DashDot);ElementFactory.Instance.CreateGraphicElement(layout,bezPl,lineSym,"New Bezier");
Create Graphic Elements
//Note:Must be on QueuedTask.Run//Build geometryList<Coordinate2D>plyCoords=newList<Coordinate2D>();plyCoords.Add(newCoordinate2D(1,7));plyCoords.Add(newCoordinate2D(2,7));plyCoords.Add(newCoordinate2D(2,6.7));plyCoords.Add(newCoordinate2D(3,6.7));plyCoords.Add(newCoordinate2D(3,6.1));plyCoords.Add(newCoordinate2D(1,6.1));Polygonpoly=PolygonBuilderEx.CreatePolygon(plyCoords);//Build geometryCoordinate2Dll=newCoordinate2D(1.0,4.75);Coordinate2Dur=newCoordinate2D(3.0,5.75);Envelopeenv=EnvelopeBuilderEx.CreateEnvelope(ll,ur);//Build geometryCoordinate2Dcoord2D=newCoordinate2D(2.0,10.0);varg1=GraphicFactory.Instance.CreateSimpleGraphic(poly);varg2=GraphicFactory.Instance.CreateSimpleGraphic(env);varg3=GraphicFactory.Instance.CreateSimpleGraphic(coord2D.ToMapPoint());varge=ElementFactory.Instance.CreateGraphicElements(layout,newList<CIMGraphic>(){g1,g2,g3},newList<string>(){"Poly","Envelope","MapPoint"},true);
Create Graphic Element using CIMGraphic
//Note: on the QueuedTask//Place symbol on the layoutMapPointlocation=MapPointBuilderEx.CreateMapPoint(newCoordinate2D(9,1));//specify a symbolvarpt_symbol=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB);//create a CIMGraphic vargraphic=newCIMPointGraphic(){Symbol=pt_symbol.MakeSymbolReference(),Location=location//center of map};//Or use GraphicFactoryvargraphicFactory=GraphicFactory.Instance.CreateSimpleGraphic(location,pt_symbol);ElementFactory.Instance.CreateGraphicElement(layout,graphic);ElementFactory.Instance.CreateGraphicElement(layout,graphicFactory);
Create Graphic Element using CIMSymbol
//Note: Must be on QueuedTask.Run//Place symbol on the layoutMapPointlocation=MapPointBuilderEx.CreateMapPoint(newCoordinate2D(9,1));//specify a symbolvarpt_symbol=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB);ElementFactory.Instance.CreateGraphicElement(layout,location,pt_symbol);
Bulk Element creation
//Note: Must be on QueuedTask.Run//List of Point graphicsvarlistGraphics=newList<CIMPointGraphic>();varlistGraphicsFactory=newList<CIMPointGraphic>();//SymbolvarpointSymbol=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.BlackRGB);//Define size of the arrayintdx=5;intdy=5;MapPointpoint=null;//Create the List of graphics for the arrayfor(introw=0;row<=dx;++row){for(intcol=0;col<=dy;++col){point=MapPointBuilderEx.CreateMapPoint(col,row);//create a CIMGraphic vargraphic=newCIMPointGraphic(){Symbol=pointSymbol.MakeSymbolReference(),Location=point};listGraphics.Add(graphic);//Or use GraphicFactoryvargraphicFactory=GraphicFactory.Instance.CreateSimpleGraphic(point,pointSymbol)asCIMPointGraphic;listGraphicsFactory.Add(graphicFactory);}}//Draw the array of graphicsvarbulkgraphics=ElementFactory.Instance.CreateGraphicElements(layout,listGraphics);varbulkgraphicsFactory=ElementFactory.Instance.CreateGraphicElements(layout,listGraphicsFactory);
Create Element using a CIMGraphicElement
//Note: Must be on QueuedTask.Run//Place symbol on the layoutMapPointpoint=MapPointBuilderEx.CreateMapPoint(newCoordinate2D(9,1));//specify a symbolvarpt_symbol=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB);//create a CIMGraphic vargraphic=newCIMGraphicElement(){Graphic=newCIMPointGraphic(){Symbol=pt_symbol.MakeSymbolReference(),Location=point//A point in the layout}};ElementFactory.Instance.CreateElement(layout,graphic);
Create point graphic with symbology
//Create a simple 2D point graphic and apply an existing point style item as the symbology.//Note: Must be on QueuedTask.Run//Build 2D point geometry Coordinate2Dcoord2D=newCoordinate2D(2.0,10.0);//(optionally) Reference a point symbol in a styleStyleProjectItemptStylePrjItm=Project.Current.GetItems<StyleProjectItem>().FirstOrDefault(item =>item.Name=="ArcGIS 2D");SymbolStyleItemptSymStyleItm=ptStylePrjItm.SearchSymbols(StyleItemType.PointSymbol,"City Hall")[0];CIMPointSymbolpointSym=ptSymStyleItm.SymbolasCIMPointSymbol;pointSym.SetSize(50);//Set symbology, create and add element to layout//An alternative simple symbol is also commented out below.//This would eliminate the four optional lines of code above that//reference a style.//CIMPointSymbol pointSym = SymbolFactory.Instance.ConstructPointSymbol(// ColorFactory.Instance.RedRGB, 25.0, SimpleMarkerStyle.Star); GraphicElementptElm=ElementFactory.Instance.CreateGraphicElement(layout,coord2D.ToMapPoint(),pointSym);ptElm.SetName("New Point");
Create line graphic with symbology
//Create a simple 2D line graphic and apply an existing line//style item as the symbology.//Note: Must be on QueuedTask.Run//Build 2d line geometryList<Coordinate2D>plCoords=newList<Coordinate2D>();plCoords.Add(newCoordinate2D(1,8.5));plCoords.Add(newCoordinate2D(1.66,9));plCoords.Add(newCoordinate2D(2.33,8.1));plCoords.Add(newCoordinate2D(3,8.5));PolylinelinePl=PolylineBuilderEx.CreatePolyline(plCoords);//(optionally) Reference a line symbol in a styleStyleProjectItemlnStylePrjItm=Project.Current.GetItems<StyleProjectItem>().FirstOrDefault(item =>item.Name=="ArcGIS 2D");SymbolStyleItemlnSymStyleItm=lnStylePrjItm.SearchSymbols(StyleItemType.LineSymbol,"Line with 2 Markers")[0];CIMLineSymbollineSym=lnSymStyleItm.SymbolasCIMLineSymbol;lineSym.SetSize(20);//Set symbology, create and add element to layout//An alternative simple symbol is also commented out below.//This would eliminate the four optional lines of code above that//reference a style.////CIMLineSymbol lineSym = SymbolFactory.Instance.ConstructLineSymbol(// ColorFactory.Instance.BlueRGB, 4.0, SimpleLineStyle.Solid); GraphicElementlineElm=ElementFactory.Instance.CreateGraphicElement(layout,linePl,lineSym);lineElm.SetName("New Line");
Create rectangle graphic with simple symbology
//Create a simple 2D rectangle graphic and apply simple fill and//outline symbols.//Note: Must be on QueuedTask.Run//Build 2D envelope geometryCoordinate2Drec_ll=newCoordinate2D(1.0,4.75);Coordinate2Drec_ur=newCoordinate2D(3.0,5.75);Enveloperec_env=EnvelopeBuilderEx.CreateEnvelope(rec_ll,rec_ur);//Set symbology, create and add element to layoutCIMStrokeoutline=SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB,5.0,SimpleLineStyle.Solid);CIMPolygonSymbolpolySym=SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.GreenRGB,SimpleFillStyle.DiagonalCross,outline);GraphicElementrecElm=ElementFactory.Instance.CreateGraphicElement(layout,rec_env,polySym,"New Rectangle");//Or use Predefined shapeGraphicElementrecElm2=ElementFactory.Instance.CreatePredefinedShapeGraphicElement(layout,PredefinedShape.Rectangle,rec_env,polySym,"New Rectangle2");
Create Text Graphic Elements
Create Point Text Element 1
//Create a simple point text element and assign basic symbology and text settings.//Note: Must be on QueuedTask.Run//Build 2D point geometryCoordinate2Dcoord2D=newCoordinate2D(3.5,10);//Set symbology, create and add element to layoutCIMTextSymbolsym=SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.RedRGB,32,"Arial","Regular");stringtextString="Point text";//use ElementInfo to set placement properties during createvarelemInfo=newElementInfo(){Anchor=Anchor.CenterPoint,Rotation=45};varptTxtElm=ElementFactory.Instance.CreateTextGraphicElement(layout,TextType.PointText,coord2D.ToMapPoint(),sym,textString,"New Point Text",true,elemInfo);//Change additional text propertiesptTxtElm.SetX(4.5);ptTxtElm.SetY(9.5);
Create Rectangle Paragraph Text Element 1
//Note: Must be on QueuedTask.Run//Create rectangle text with background and border symbology. //Build 2D polygon geometryList<Coordinate2D>plyCoords=newList<Coordinate2D>();plyCoords.Add(newCoordinate2D(3.5,7));plyCoords.Add(newCoordinate2D(4.5,7));plyCoords.Add(newCoordinate2D(4.5,6.7));plyCoords.Add(newCoordinate2D(5.5,6.7));plyCoords.Add(newCoordinate2D(5.5,6.1));plyCoords.Add(newCoordinate2D(3.5,6.1));Polygonpoly=PolygonBuilderEx.CreatePolygon(plyCoords);//Set symbology, create and add element to layout//Also notice how formatting tags are using within the text string.CIMTextSymbolsym=SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.GreyRGB,10,"Arial","Regular");stringtext="Some Text String that is really long and is "+"<BOL>forced to wrap to other lines</BOL> so that "+"we can see the effects."asString;GraphicElementpolyTxtElm=ElementFactory.Instance.CreateTextGraphicElement(layout,TextType.RectangleParagraph,poly,sym,text,"Polygon Paragraph");//(Optionally) Modify paragraph border CIMGraphicpolyTxtGra=polyTxtElm.GetGraphic();CIMParagraphTextGraphiccimPolyTxtGra=polyTxtGraasCIMParagraphTextGraphic;cimPolyTxtGra.Frame.BorderSymbol=newCIMSymbolReference();cimPolyTxtGra.Frame.BorderSymbol.Symbol=SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.GreyRGB,1.0,SimpleLineStyle.Solid);polyTxtElm.SetGraphic(polyTxtGra);
Create a Dynamic Point Text Element
//Create a dynamic text element.//Set the string with tags and the locationStringtitle=@"<dyn type = ""page"" property = ""name"" />";Coordinate2DllTitle=newCoordinate2D(6,2.5);//Create with default text properties//Note: Must be on QueuedTask.RunTextElementtitleGraphics=ElementFactory.Instance.CreateTextGraphicElement(layout,TextType.PointText,llTitle.ToMapPoint(),null,title)asTextElement;//Modify the text propertiestitleGraphics.SetTextProperties(newTextProperties(title,"Arial",24,"Bold"));
Create Point Text Element 2
//Note: Must be on QueuedTask.Run//Build geometryCoordinate2Dcoord2D=newCoordinate2D(3.5,10);//Set symbology, create and add element to layoutCIMTextSymbolsym=SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.RedRGB,32,"Arial","Regular");stringtextString="Point text";varelemInfo=newElementInfo(){Anchor=Anchor.BottomLeftCorner};GraphicElementptTxtElm=ElementFactory.Instance.CreateTextGraphicElement(layout,TextType.PointText,coord2D.ToMapPoint(),sym,textString,"New Point Text",true,elemInfo);
Create Polygon Paragraph Text Element
//Note: Must be on QueuedTask.Run//Build geometryList<Coordinate2D>plyCoords=newList<Coordinate2D>();plyCoords.Add(newCoordinate2D(3.5,7));plyCoords.Add(newCoordinate2D(4.5,7));plyCoords.Add(newCoordinate2D(4.5,6.7));plyCoords.Add(newCoordinate2D(5.5,6.7));plyCoords.Add(newCoordinate2D(5.5,6.1));plyCoords.Add(newCoordinate2D(3.5,6.1));Polygonpoly=PolygonBuilderEx.CreatePolygon(plyCoords);//Set symbology, create and add element to layoutCIMTextSymbolsym=SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.GreyRGB,10,"Arial","Regular");stringtext="Some text string that is really long and "+"<BOL>wraps to other lines</BOL>"+" so that we can see the effects.";varge=ElementFactory.Instance.CreateTextGraphicElement(layout,TextType.PolygonParagraph,poly,sym,text,"New Polygon Text",true);
Create Rectangle Paragraph Text Element 2
//Note: Must be on QueuedTask.Run//Build geometryCoordinate2Dll=newCoordinate2D(3.5,4.75);Coordinate2Dur=newCoordinate2D(5.5,5.75);Envelopeenv=EnvelopeBuilderEx.CreateEnvelope(ll,ur);//Set symbology, create and add element to layoutCIMTextSymbolsym=SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.WhiteRGB,10,"Arial","Regular");stringtext="Some text string that is really long and "+"<BOL>wraps to other lines</BOL>"+" so that we can see the effects.";//(Optionally) Modify border and background with 50% transparency //CIMGraphic recTxtGra = recTxtElm.Graphic;//CIMParagraphTextGraphic cimRecTxtGra = recTxtGra as CIMParagraphTextGraphic;//CIMSymbolReference cimRecTxtBorder = cimRecTxtGra.Frame.BorderSymbol;////CIMLineSymbol lineSym = SymbolFactory.Instance.ConstructLineSymbol(// ColorFactory.Instance.BlackRGB, 1.0, SimpleLineStyle.Solid);//cimRecTxtBorder.Symbol = lineSym;////CIMSymbolReference cimRecTxtBkgrd = cimRecTxtGra.Frame.BackgroundSymbol;//CIMPolygonSymbol polySym = SymbolFactory.Instance.ConstructPolygonSymbol(// ColorFactory.Instance.GreyRGB, SimpleFillStyle.Solid);////CIMColor symCol = polySym.GetColor(IElementContainer container);//symCol.SetAlphaValue(50);//cimRecTxtBkgrd.Symbol = polySym;//recTxtElm.SetGraphic(recTxtGra);varge=ElementFactory.Instance.CreateTextGraphicElement(layout,TextType.RectangleParagraph,env,sym,text,"New Rectangle Text");
Create Circle Text Element
//Note: Must be on QueuedTask.Run(() => { ...//Build geometryCoordinate2Dcenter=newCoordinate2D(4.5,4);vareabCir=newEllipticArcBuilderEx(center,0.5,ArcOrientation.ArcClockwise);varcir=eabCir.ToSegment();varpoly=PolygonBuilderEx.CreatePolygon(PolylineBuilderEx.CreatePolyline(cir,AttributeFlags.AllAttributes));//Set symbology, create and add element to layoutCIMTextSymbolsym=SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.GreenRGB,10,"Arial","Regular");stringtext="Circle, circle, circle";GraphicElementcirTxtElm=ElementFactory.Instance.CreateTextGraphicElement(layout,TextType.CircleParagraph,poly,sym,text,"New Circle Text",false);
Create Bezier Text Element
//Note: Must be on QueuedTask.Run//Build geometryCoordinate2Dpt1=newCoordinate2D(3.5,7.5);Coordinate2Dpt2=newCoordinate2D(4.16,8);Coordinate2Dpt3=newCoordinate2D(4.83,7.1);Coordinate2Dpt4=newCoordinate2D(5.5,7.5);varbez=newCubicBezierBuilderEx(pt1,pt2,pt3,pt4);varbezSeg=bez.ToSegment();PolylinebezPl=PolylineBuilderEx.CreatePolyline(bezSeg,AttributeFlags.AllAttributes);//Set symbology, create and add element to layoutCIMTextSymbolsym=SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.BlackRGB,24,"Comic Sans MS","Regular");varge=ElementFactory.Instance.CreateTextGraphicElement(layout,TextType.SplinedText,bezPl,sym,"this is the bezier text","New Bezier Text",true,newElementInfo(){Anchor=Anchor.CenterPoint});
Create Ellipse Text Element
//Note: Must be on QueuedTask.Run//Build geometryCoordinate2Dcenter=newCoordinate2D(4.5,2.75);vareabElp=newEllipticArcBuilderEx(center,0,1,0.45,ArcOrientation.ArcClockwise);varellipse=eabElp.ToSegment();varpoly=PolygonBuilderEx.CreatePolygon(PolylineBuilderEx.CreatePolyline(ellipse,AttributeFlags.AllAttributes));//Set symbology, create and add element to layoutCIMTextSymbolsym=SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.BlueRGB,10,"Arial","Regular");stringtext="Ellipse, ellipse, ellipse";GraphicElementge=ElementFactory.Instance.CreateTextGraphicElement(layout,TextType.PolygonParagraph,poly,sym,text,"New Ellipse Text",false);
Create Predefined Shapes And Arrows
Create Predefined Shape Graphic Element
PredefinedShapeshapeType=PredefinedShape.Circle;//Note: Must be on QueuedTask.Run//PredefinedShape shapeType =// PredefinedShape.Circle | Cloud | Cross |Circle | Triangle | ... ;//Build geometryCoordinate2Dll=newCoordinate2D(4,2.5);Coordinate2Dur=newCoordinate2D(6,4.5);Envelopeenv=EnvelopeBuilderEx.CreateEnvelope(ll,ur);varoutline=SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlueRGB,2);varpoly_sym=SymbolFactory.Instance.ConstructPolygonSymbol(null,outline);varge=ElementFactory.Instance.CreatePredefinedShapeGraphicElement(layout,shapeType,env.Center,env.Width,env.Height,poly_sym,shapeType.ToString(),true);
Create Predefined Shape Graphic Element 2
//Note: Must be on QueuedTask.Run//Build geometryCoordinate2Dll=newCoordinate2D(6.5,7);Coordinate2Dur=newCoordinate2D(9,9);Envelopeenv=EnvelopeBuilderEx.CreateEnvelope(ll,ur);varoutline=SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.GreenRGB,2);varpoly_sym=SymbolFactory.Instance.ConstructPolygonSymbol(null,outline);varge=ElementFactory.Instance.CreatePredefinedShapeGraphicElement(layout,PredefinedShape.RoundedRectangle,env,poly_sym,"Rounded Rect",true);
Create Predefined Shape Graphic Element 3
//Note: Must be on QueuedTask.Run//Build geometryCoordinate2Dcenter=newCoordinate2D(2,2.75);vareabElp=newEllipticArcBuilderEx(center,0,1,0.45,ArcOrientation.ArcClockwise);varellipse=eabElp.ToSegment();//Set symbology, create and add element to layoutCIMStrokeoutline=SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.GreenRGB,2.0,SimpleLineStyle.Dot);CIMPolygonSymbolellipseSym=SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.GreyRGB,SimpleFillStyle.Vertical,outline);varpoly=PolygonBuilderEx.CreatePolygon(PolylineBuilderEx.CreatePolyline(ellipse,AttributeFlags.AllAttributes));varge=ElementFactory.Instance.CreatePredefinedShapeGraphicElement(layout,PredefinedShape.Ellipse,poly.Extent.Center,0,0,ellipseSym,"New Ellipse2",false,newElementInfo(){Anchor=Anchor.TopRightCorner});
Create Line Arrow Element
//Note: Must be on QueuedTask.Run(() => { ...//Build geometryList<Coordinate2D>plCoords=newList<Coordinate2D>();plCoords.Add(newCoordinate2D(1,8.5));plCoords.Add(newCoordinate2D(1.66,9));plCoords.Add(newCoordinate2D(2.33,8.1));plCoords.Add(newCoordinate2D(3,8.5));PolylinelinePl=PolylineBuilderEx.CreatePolyline(plCoords);vararrowInfo=newArrowInfo(){ArrowHeadKey=ArrowInfo.DefaultArrowHeadKeys[8],ArrowOnBothEnds=true,ArrowSizePoints=24,LineWidthPoints=12};//Create and add element to layoutGraphicElementlineElm=ElementFactory.Instance.CreateArrowGraphicElement(layout,linePl,arrowInfo,"Arrow Line",true,newElementInfo(){Rotation=15.0});//lineElm.SetName("New Line");
Picture Elements
Create Picture Graphic Element using CIMSymbol
//Note: Must be on QueuedTask.Run(() => { ...//Build geometryCoordinate2Dll=newCoordinate2D(0.5,1);Coordinate2Dur=newCoordinate2D(2.5,2);Envelopeenv=EnvelopeBuilderEx.CreateEnvelope(ll,ur);//Create and add element to layoutstringpicPath=System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),"SamplePicture.jpg");varpic_gr=ElementFactory.Instance.CreatePictureGraphicElement(layout,env.Center,picPath,"New Picture",true,newElementInfo(){Anchor=Anchor.CenterPoint});
Create a new picture element with advanced symbol settings
//Create a picture element and also set background and border symbology.//Note: Must be on QueuedTask.Run//Build 2D envelope geometryCoordinate2Dpic_ll=newCoordinate2D(6,1);Coordinate2Dpic_ur=newCoordinate2D(8,2);Envelopeenv=EnvelopeBuilderEx.CreateEnvelope(pic_ll,pic_ur);//Create and add element to layoutstringpicPath=@"C:\Temp\WhitePass.jpg";GraphicElementpicElm=ElementFactory.Instance.CreatePictureGraphicElement(layout,env,picPath,"New Picture");//(Optionally) Modify the border and shadow CIMGraphicpicGra=picElm.GetGraphic();CIMPictureGraphiccimPicGra=picGraasCIMPictureGraphic;cimPicGra.Frame.BorderSymbol=newCIMSymbolReference();cimPicGra.Frame.BorderSymbol.Symbol=SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlueRGB,2.0,SimpleLineStyle.Solid);cimPicGra.Frame.ShadowSymbol=newCIMSymbolReference();cimPicGra.Frame.ShadowSymbol.Symbol=SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.BlackRGB,SimpleFillStyle.Solid);//Update the elementpicElm.SetGraphic(picGra);
Create MapFrame and Surrounds
Create Map Frame and Set Camera
//Create a map frame and set its camera by zooming to the extent of an existing bookmark.//Construct on the worker thread//Build 2D envelope geometryCoordinate2Dmf_ll=newCoordinate2D(6.0,8.5);Coordinate2Dmf_ur=newCoordinate2D(8.0,10.5);Envelopemf_env=EnvelopeBuilderEx.CreateEnvelope(mf_ll,mf_ur);//Reference map, create MF and add to layoutMapProjectItemmapPrjItem=Project.Current.GetItems<MapProjectItem>().FirstOrDefault(item =>item.Name.Equals("Map"));MapmfMap=mapPrjItem.GetMap();Bookmarkbookmark=mfMap.GetBookmarks().FirstOrDefault(
b =>b.Name=="Great Lakes");MapFramemfElm=ElementFactory.Instance.CreateMapFrameElement(layout,mf_env,mfMap,"New Map Frame");//Zoom to bookmarkmfElm.SetCamera(bookmark);
Create Legend
//Create a legend for an associated map frame.//Note: Must be on QueuedTask.Run//Build 2D envelope geometryCoordinate2Dleg_ll=newCoordinate2D(6,2.5);Coordinate2Dleg_ur=newCoordinate2D(8,4.5);Envelopeleg_env=EnvelopeBuilderEx.CreateEnvelope(leg_ll,leg_ur);//Reference MF, create legend and add to layoutmapFrame=layout.FindElement("New Map Frame")asMapFrame;if(mapFrame==null){//TODO handle null map framereturn;}varlegendInfo=newLegendInfo(){MapFrameName=mapFrame.Name};LegendlegendElm=ElementFactory.Instance.CreateMapSurroundElement(layout,leg_env,legendInfo,"New Legend")asLegend;
Create Scale Bar From StyleItem
//Create a scale bar using a style.//Search for a style project item by nameStyleProjectItemarcgis_2dStyle=Project.Current.GetItems<StyleProjectItem>().First(si =>si.Name=="ArcGIS 2D");//Note: Must be on QueuedTask.Run//Reference the specific scale bar by name ScaleBarStyleItemscaleBarItem=arcgis_2dStyle.SearchScaleBars("Double Alternating Scale Bar").FirstOrDefault();//Reference the map frame and define the locationMapFramemyMapFrame=layout.FindElement("Map Frame")asMapFrame;Coordinate2Dcoord2D=newCoordinate2D(10.0,7.0);//Construct the scale barvarsbarInfo=newScaleBarInfo(){MapFrameName=myMapFrame.Name,ScaleBarStyleItem=scaleBarItem};ElementFactory.Instance.CreateMapSurroundElement(layout,coord2D.ToMapPoint(),sbarInfo);
Create North Arrow From StyleItem 1
//Create a north arrow using a style.//Search for a style project item by nameStyleProjectItemarcgis2dStyles=Project.Current.GetItems<StyleProjectItem>().First(si =>si.Name=="ArcGIS 2D");//Construct on the worker threadNorthArrowStyleItemnaStyleItem=arcgis2dStyles.SearchNorthArrows("ArcGIS North 13").FirstOrDefault();//Reference the map frame and define the locationMapFramenewFrame=layout.FindElement("New Map Frame")asMapFrame;Coordinate2DnArrow=newCoordinate2D(6,2.5);//Construct the north arrowvarnaInfo=newNorthArrowInfo(){MapFrameName=newFrame.Name,NorthArrowStyleItem=naStyleItem};varnewNorthArrow=ElementFactory.Instance.CreateMapSurroundElement(layout,nArrow.ToMapPoint(),naInfo);
Create Table Frame
//Create a table frame.//Note: Must be on QueuedTask.Run//Build 2D envelope geometryCoordinate2Drec_ll=newCoordinate2D(1.0,3.5);Coordinate2Drec_ur=newCoordinate2D(7.5,4.5);Enveloperec_env=EnvelopeBuilderEx.CreateEnvelope(rec_ll,rec_ur);//Reference map frame and layerMapFramemf=layout.FindElement("Map Frame")asMapFrame;FeatureLayerlyr=mf.Map.FindLayers("GreatLakes").First()asFeatureLayer;//Build fields listvarfields=new[]{"NAME","Shape_Area","Shape_Length"};//Construct the table framevartableFrameInfo=newTableFrameInfo(){FieldNames=fields,MapFrameName=mf.Name,MapMemberUri=lyr.URI};vartabFrame=ElementFactory.Instance.CreateMapSurroundElement(layout,rec_env,tableFrameInfo)asTableFrame;
Create Map Frame 1
//Note: QueuedTask.Run//Build geometryCoordinate2Dll=newCoordinate2D(2.0,4.5);Coordinate2Dur=newCoordinate2D(4.0,6.5);Envelopeenv=EnvelopeBuilderEx.CreateEnvelope(ll,ur);//Reference map, create MF and add to layoutMapFramemfElm=ElementFactory.Instance.CreateMapFrameElement(layout,env,map);
Create Map Frame 2
//Note: Must be on QueuedTask.Run(() => { ...//Build geometryCoordinate2Dll=newCoordinate2D(4.0,2.5);Coordinate2Dur=newCoordinate2D(7.0,5.5);Envelopeenv=EnvelopeBuilderEx.CreateEnvelope(ll,ur);MapFramemfElm=ElementFactory.Instance.CreateMapFrameElement(layout,env.Center,map);
Create Legend 2
//Note: Must be on QueuedTask.Run//Build geometryCoordinate2Dll=newCoordinate2D(6,2.5);Coordinate2Dur=newCoordinate2D(8,4.5);Envelopeenv=EnvelopeBuilderEx.CreateEnvelope(ll,ur);//Reference MF, create legend and add to layoutMapFramemf=layout.FindElement("Map Frame")asMapFrame;varsurroundInfo=newLegendInfo(){MapFrameName=mf.Name};varlegendElm=ElementFactory.Instance.CreateMapSurroundElement(layout,env.Center,surroundInfo)asLegend;legendElm.SetName("New Legend");
Create North Arrow From StyleItem 2
//Note: Must be on QueuedTask.Run//Build geometryCoordinate2Dcenter=newCoordinate2D(7,5.5);//Reference a North Arrow in a styleStyleProjectItemstylePrjItm=Project.Current.GetItems<StyleProjectItem>().FirstOrDefault(item =>item.Name=="ArcGIS 2D");NorthArrowStyleItemnaStyleItm=stylePrjItm.SearchNorthArrows("ArcGIS North 10")[0];//Reference MF, create north arrow and add to layout varmf=layout.FindElement("Map Frame")asMapFrame;varnarrow_info=newNorthArrowInfo(){MapFrameName=mf.Name,NorthArrowStyleItem=naStyleItm};vararrowElm=(NorthArrow)ElementFactory.Instance.CreateMapSurroundElement(layout,center.ToMapPoint(),narrow_info)asNorthArrow;arrowElm.SetName("New North Arrow");arrowElm.SetHeight(1.75);arrowElm.SetX(7);arrowElm.SetY(6);
Create Table Frame 2
//Note: Must be on QueuedTask.Run//Build geometryCoordinate2Dll=newCoordinate2D(1,1);Coordinate2Dur=newCoordinate2D(4,4);Envelopeenv=EnvelopeBuilderEx.CreateEnvelope(ll,ur);vartableFrameInfo=newTableFrameInfo(){MapFrameName="Map Frame",MapMemberUri="CIMPATH=USNationalParks/NationalParks.json"};varattribs=newList<CIMStringMap>();for(inti=1;i<6;i++){attribs.Add(newCIMStringMap{Key=$"Key {i}",Value=$"Value {i}"});}varelemInfo=newElementInfo(){CustomProperties=attribs};vartableFrameElem=ElementFactory.Instance.CreateMapSurroundElement(layout,env.Center,tableFrameInfo,"New Table Frame",false,elemInfo)asTableFrame;
Create Scale Bar
//Note: Must be on QueuedTask.Run//Build geometryCoordinate2Dll=newCoordinate2D(5.0,6);Coordinate2Dur=newCoordinate2D(6.0,7);EnvelopesbEnv=EnvelopeBuilderEx.CreateEnvelope(ll,ur);//Reference a Scale Bar in a styleStyleProjectItemstylePrjItm=Project.Current.GetItems<StyleProjectItem>().FirstOrDefault(item =>item.Name=="ArcGIS 2D");ScaleBarStyleItemsbStyleItm=stylePrjItm.SearchScaleBars("Alternating Scale Bar 1")[0];//ScaleBarStyleItem sbStyleItm = stylePrjItm.SearchScaleBars(// "Double Alternating Scale Bar 1")[0];//ScaleBarStyleItem sbStyleItm = stylePrjItm.SearchScaleBars(// "Hollow Scale Bar 1")[0];//Create Scale BarScaleBarInfosbInfo=newScaleBarInfo(){MapFrameName=mapFrame.Name,};varsbElm=ElementFactory.Instance.CreateMapSurroundElement(layout,sbEnv,sbInfo)asScaleBar;
Create Scale Line
//Note: Must be on QueuedTask.Run//Build geometryCoordinate2Dll=newCoordinate2D(5.0,8);Coordinate2Dur=newCoordinate2D(6.0,9);EnvelopesbEnv=EnvelopeBuilderEx.CreateEnvelope(ll,ur);//Reference a Scale Bar in a styleStyleProjectItemstylePrjItm=Project.Current.GetItems<StyleProjectItem>().FirstOrDefault(item =>item.Name=="ArcGIS 2D");ScaleBarStyleItemsbStyleItm=stylePrjItm.SearchScaleBars("Scale Line 1")[0];//ScaleBarStyleItem sbStyleItm = stylePrjItm.SearchScaleBars(// "Stepped Scale Line")[0];//ScaleBarStyleItem sbStyleItm = stylePrjItm.SearchScaleBars(// "Scale Line 2")[0];//Create Scale BarScaleBarInfosbInfo=newScaleBarInfo(){MapFrameName=mapFrame.Name,ScaleBarStyleItem=sbStyleItm};varsbElm=ElementFactory.Instance.CreateMapSurroundElement(layout,sbEnv,sbInfo,"ScaleBar Line")asScaleBar;
Group Elements
Creating empty group elements
//Create an empty group element at the root level of the contents pane//Note: Must be on QueuedTask.Run//container is IElementContainer - GroupLayer or LayoutGroupElementgrp1=ElementFactory.Instance.CreateGroupElement(layout,null,"Group");// *** or ***//Create a group element inside another group element//Find an existing group element//container is IElementContainer - GroupLayer or LayoutGroupElementexistingGroup=layout.FindElement("Group")asGroupElement;//Create on worker threadGroupElementgrp2=ElementFactory.Instance.CreateGroupElement(existingGroup,null,"Group in Group");
Create a group element with elements
//Create a group with a list of elements at the root level of the contents pane.//Find an existing elements//container is IElementContainer - GroupLayer or Layoutvarelem1=layout.FindElement("Polygon 1");varelem2=layout.FindElement("Bezier Text");varelem3=layout.FindElement("Cloud Shape 2");//Construct a list and add the elementsvarelmList=newList<Element>{elem1,elem2,elem3};//Note: Must be on QueuedTask.RunGroupElementgroupWithListOfElementsAtRoot=ElementFactory.Instance.CreateGroupElement(layout,elmList,"Group with list of elements at root");// *** or ***//Create a group using a list of element names at the root level of the contents pane.//List of element namesvarelmNameList=new[]{"Para Text1","Line 3"};//Note: Must be on QueuedTask.RunvarelemToGroup=layout.FindElements(elmNameList);GroupElementgroupWithListOfElementNamesAtRoot=ElementFactory.Instance.CreateGroupElement(layout,elemToGroup,"Group with list of element names at root");
Layout Elements and Selection
Find an element on a layout
//Find an element on a layout.//Note: Must be on QueuedTask.Run// Reference and load the layout associated with the layout itemLayoutmylayout=layoutItem.GetLayout();if(mylayout!=null){//Find a single specific elementElementrect=mylayout.FindElement("Rectangle")asElement;//Or use the Elements collectionElementrect2=mylayout.Elements.FirstOrDefault(item =>item.Name.Equals("Rectangle"));}
Find layout elements
//Note: Must be on QueuedTask.Run//Find elements by namevarlayoutElementsToFind=layout.FindElements(newList<string>(){"Point 1","Line 3","Text 1"});//Get the collection of elements from the page layout. Nesting within GroupElement is preserved.varelementCollection=layout.GetElements();//Get the collection of Element from the page layout as a flattened list. Nested groups within GroupElement are not preserved.varelements=layout.GetElementsAsFlattenedList();//Convert collection of the elements to a collection of GraphicElements.vargraphicElements=elements.ToList().ConvertAll(x =>(GraphicElement)x);//Find elements by type//Find all point graphics in the LayoutvarpointGraphics=graphicElements.Where(elem =>elem.GetGraphic()isCIMPointGraphic);//Find all line graphics in the Graphics LayervarlineGraphics=graphicElements.Where(elem =>elem.GetGraphic()isCIMLineGraphic);////Find all polygon graphics in the Graphics LayervarpolyGraphics=graphicElements.Where(elem =>elem.GetGraphic()isCIMPolygonGraphic);////Find all text graphics in the Graphics LayervartextGraphics=graphicElements.Where(elem =>elem.GetGraphic()isCIMTextGraphic);////Find all picture graphics in the Graphics LayervarpictureGraphic=graphicElements.Where(elem =>elem.GetGraphic()isCIMPictureGraphic);
Update element properties
//Update an element's properties.//Note: Must be on QueuedTask.Run//Find a single specific elementelement=layout.FindElement("Rectangle")asElement;// update an element's nameelement.SetName("New Name");// update and element's visibilityelement.SetVisible(true);
Get element selection count
//Get element's selection count.//Count the number of selected elements on the active layout viewLayoutViewactiveLayoutView=LayoutView.Active;if(activeLayoutView!=null){varselectedElements=activeLayoutView.GetSelectedElements();ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show($@"Selected elements: {selectedElements.Count}");}
Set element selection
//Set the active layout view's selection to include 2 rectangle elements.//Reference the active view LayoutViewactiveLayoutView=LayoutView.Active;if(activeLayoutView!=null){//Note: Must be on QueuedTask.Run//Reference the layoutLayoutlyt=activeLayoutView.Layout;//Reference the two rectangle elementsElementrec=lyt.FindElement("Rectangle");Elementrec2=lyt.FindElement("Rectangle 2");//Construct a list and add the elementsList<Element>elmList=newList<Element>{rec,rec2};//Set the selectionactiveLayoutView.SelectElements(elmList);}
UnSelect elements on the Layout
//Unselect one element.varelementToUnSelect=layout.FindElements(newList<string>(){"MyPoint"}).FirstOrDefault();layout.UnSelectElement(elementToUnSelect);//Unselect multiple elements.varelementsToUnSelect=layout.FindElements(newList<string>(){"Point 1","Line 3","Text 1"});layout.UnSelectElements(elementsToUnSelect);
UnSelect elements on the LayoutView
//Unselect one element.varelementToUnSelectInView=layout.FindElements(newList<string>(){"MyPoint"}).FirstOrDefault();layoutView.UnSelectElement(elementToUnSelectInView);//Unselect multiple elements.varelementsToUnSelectInView=layout.FindElements(newList<string>(){"Point 1","Line 3","Text 1"});layoutView.UnSelectElements(elementsToUnSelectInView);
Clear the selection in a layout view
//If the a layout view is active, clear its selectionLayoutViewactiveLayoutView=LayoutView.Active;if(activeLayoutView!=null){activeLayoutView.ClearElementSelection();}
Clear the selection in a layout
//Clear the layout selection.layout.ClearElementSelection();
Copy Layout Elements
//Note: Must be on QueuedTask.Runvarelems=layout.FindElements(newList<string>(){"Point 1","Line 3","Text 1"});varcopiedElements=layout.CopyElements(elems);
Delete Layout Elements
//Note: Must be on QueuedTask.RunvarelementsToRemove=layout.GetSelectedElements();layout.DeleteElements(elementsToRemove);
Delete an element or elements on a layout
//Delete an element or elements on a layout.//Note: Must be on QueuedTask.Run//Delete a specific element on a layout//Find a single specific elementElementrect=layout.FindElement("Rectangle")asElement;layout.DeleteElement(rect);//Or delete a group of elements using a filterlayout.DeleteElements(item =>item.Name.Contains("Clone"));//Or delete all elements on a layoutlayout.DeleteElements(item =>true);
Zoom to elements
LayoutViewlytView=LayoutView.Active;//Zoom to an elementvarelementToZoomTo=layout.FindElements(newList<string>(){"MyPoint"}).FirstOrDefault();lytView.ZoomToElement(elementToZoomTo);//Zoom to multiple elements.varelementsToZoomTo=layout.FindElements(newList<string>(){"Point 1","Line 3","Text 1"});lytView.ZoomToElements(elementsToZoomTo);
Set halo property of north arrow
//Set the CIM halo properties of a north arrow.//Reference the first selected north arrow elementvarnorthArrow=LayoutView.Active.GetSelectedElements().OfType<NorthArrow>().First();//Note: Must be on QueuedTask.Run//Get definition of north arrow...varcim=northArrow.GetDefinition()asCIMMarkerNorthArrow;//this halo symbol is 50% transparent, no outline (i.e. 0 width)//First construct a polygon symbol to use in the Halo//Polygon symbol will need a fill and a strokevarpolyFill=SymbolFactory.Instance.ConstructSolidFill(ColorFactory.Instance.CreateRGBColor(0,0,0,50));varpolyStroke=SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB,0);varhaloPoly=SymbolFactory.Instance.ConstructPolygonSymbol(polyFill,polyStroke);//Set the north arrow definition of HaloSymbol and HaloSize ((CIMPointSymbol)cim.PointSymbol.Symbol).HaloSymbol=haloPoly;((CIMPointSymbol)cim.PointSymbol.Symbol).HaloSize=3;//size of the halo//Apply the CIM changes back to the elementnorthArrow.SetDefinition(cim);
Grouping and Ordering Graphic Elements
Group Graphic Elements
//Note: Must be on QueuedTask.RunvarelemsToGroup=layout.GetSelectedElements();//Note: run within the QueuedTask//group elementsvarnewGroupElement=layout.GroupElements(elemsToGroup);
Un-Group Graphic Elements
//Note: Must be on QueuedTask.RunvarselectedElements=layout.GetSelectedElements().ToList();if(selectedElements?.Any()==false)//must be at least 1.return;varelementsToUnGroup=newList<GroupElement>();//All selected elements should be grouped elements.if(selectedElements.Count()==selectedElements.OfType<GroupElement>().Count()){//Convert to a GroupElement list.elementsToUnGroup=selectedElements.ConvertAll(x =>(GroupElement)x);}if(elementsToUnGroup.Count()==0)return;//UnGroup many grouped elementslayout.UnGroupElements(elementsToUnGroup);//Ungroup one grouped elementlayout.UnGroupElement(elementsToUnGroup.FirstOrDefault());
Parent of GroupElement
//check the parentvarparent=groupElement.Elements.First().GetParent();//will be the group element//top-most parent//will be a GraphicsLayer or Layoutvartop_most=groupElement.Elements.First().GetParent(true);
Children in a Group Element
// Nested groups within ArcGIS.Desktop.Layouts.GroupElement are not preserved.varchildren=groupElement.GetElementsAsFlattenedList();
Ordering: Send backward and Bring forward
//Note: Must be on QueuedTask.Run//get the current selection setvarsel_elems=layout.GetSelectedElements();//can they be brought forward? This will also check that all elements have the same parentif(layout.CanBringForward(sel_elems)){//bring forwardlayout.BringForward(sel_elems);//bring to front (of parent)//graphicsLayer.BringToFront(sel_elems);}elseif(layout.CanSendBackward(sel_elems)){//send backlayout.SendBackward(sel_elems);//send to the back (of parent)//graphicsLayer.SendToBack(sel_elems);}
Get Z-Order
varselElementsZOrder=layout.GetSelectedElements();//list out the z orderforeach(vareleminselElementsZOrder)System.Diagnostics.Debug.WriteLine($"{elem.Name}: z-order {elem.ZOrder}");
Update Layout Elements
Update text element properties
//Update text element properties for an existing text element.//Note: Must be on QueuedTask.Run// Reference and load the layout associated with the layout itemif(layout!=null){// Reference a text element by nameTextElementtxtElm=layout.FindElement("MyTextElement")asTextElement;if(txtElm!=null){doublex=2.0;doubley=3.0;// Change placement propertiestxtElm.SetAnchor(Anchor.CenterPoint);txtElm.SetX(x);txtElm.SetY(y);// Change TextPropertiesTextPropertiestxtProperties=newTextProperties("Hello world","Times New Roman",48,"Regular");txtElm.SetTextProperties(txtProperties);}
Update a picture element
//Update a picture element.//Note: Must be on QueuedTask.Run// Reference a picture element by namePictureElementpicElm=layout.FindElement("MyPicture")asPictureElement;// Change the path to a new sourceif(picElm!=null)picElm.SetSourcePath(@"D:\MyData\Pics\somePic.jpg");
Apply a Background Color to a MapFrame
//Apply a background color to the map frame element using the CIM.//Note: Must be on QueuedTask.Run//Get the map frame's definition in order to modify the background.varmapFrameDefn=mapFrame.GetDefinition()asCIMMapFrame;//Construct the polygon symbol to use to create a backgroundvarpolySymbol=SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.BlueRGB,SimpleFillStyle.Solid);//Set the backgroundmapFrameDefn.GraphicFrame.BackgroundSymbol=polySymbol.MakeSymbolReference();//Set the map frame definitionmapFrame.SetDefinition(mapFrameDefn);
Update a map surround
//Update a map surround.//Note: Must be on QueuedTask.Run// Reference and load the layout associated with the layout item// Reference a scale bar element by nameMapSurroundscaleBar=layout.FindElement("MyScaleBar")asMapSurround;// Reference a map frame element by nameMapFramemf=layout.FindElement("MyMapFrame")asMapFrame;if((scaleBar!=null)&&(mf!=null))//Set the scale bar to the newly referenced map framescaleBar.SetMapFrame(mf);
Lock an element
// The Locked property is displayed in the TOC as a lock symbol next// to each element. If locked the element can't be selected in the layout// using the graphic selection tools.//Note: Must be on QueuedTask.Run//Reference an element if(element!=null){// Modify the Locked property via the CIMCIMElementCIMElement=element.GetDefinition()asCIMElement;CIMElement.Locked=true;element.SetDefinition(CIMElement);}
Update an elements transparency
//Update an element's transparency using the CIM.//Note: Must be on QueuedTask.Run// Reference a element by nameGraphicElementgraphicElement=layout.FindElement("MyElement")asGraphicElement;if(graphicElement!=null){// Modify the Transparency property that exists only in the CIMGraphic class.CIMGraphicCIMGraphic=graphicElement.GetGraphic()asCIMGraphic;CIMGraphic.Transparency=50;// mark it 50% transparentgraphicElement.SetGraphic(CIMGraphic);}
Clone an element
//Clone a layout graphic element and apply an offset.//Note: Must be on QueuedTask.Run// Reference a graphic element by nameGraphicElementgraphicElement=layout.FindElement("MyElement")asGraphicElement;if(graphicElement!=null){//Clone and set the new x,yGraphicElementcloneElement=graphicElement.Clone("Clone");doublexOffset=0;doubleyOffset=0;cloneElement.SetX(cloneElement.GetX()+xOffset);cloneElement.SetY(cloneElement.GetY()+yOffset);}
Style Layout Elements
Apply a style to a North Arrow
//Note: Must be on QueuedTask.Run//Get the Style project items in the projectvarstyleProjectItems=Project.Current?.GetItems<StyleProjectItem>();//Get the ArcGIS 2D Style Project ItemvarstyleProjectItem=styleProjectItems.FirstOrDefault(s =>s.Name=="ArcGIS 2D");if(styleProjectItem==null)return;//Get the north arrow style item you needvarnorthArrowStyleItem=styleProjectItem.SearchSymbols(StyleItemType.NorthArrow,"ArcGIS North 18").FirstOrDefault();if(northArrowStyleItem==null)return;//Select a North arrow layout elementvarnorthArrowElement=layout.GetSelectedElements().OfType<NorthArrow>().FirstOrDefault();if(northArrowElement!=null){//Check if the input style can be applied to the elementif(northArrowElement.CanApplyStyle(northArrowStyleItem))//Apply the stylenorthArrowElement.ApplyStyle(northArrowStyleItem);}
Apply a style to Grid and Graticules
//Note: Must be on QueuedTask.Run//Get the Style project items in the projectvarstyleProjectItems=Project.Current?.GetItems<StyleProjectItem>();//Get the ArcGIS 2D Style Project ItemvarstyleProjectItem=styleProjectItems.OfType<StyleProjectItem>().FirstOrDefault(s =>s.Name=="ArcGIS 2D");if(styleProjectItem==null)return;//Get the grid style item you needvargridStyleItem=styleProjectItem.SearchSymbols(StyleItemType.Grid,"Blue Vertical Label Graticule").FirstOrDefault();if(gridStyleItem==null)return;varsymbolItemName=gridStyleItem.Name;vargirdGraticuleObject=gridStyleItem.GetObject()asCIMMapGrid;varcmf=mapFrame.GetDefinition()asCIMMapFrame;//note, if page units are _not_ inches then grid's gridline//lengths and offsets would need to be converted to the page unitsvarmapGrids=newList<CIMMapGrid>();if(cmf.Grids!=null)mapGrids.AddRange(cmf.Grids);switch(girdGraticuleObject){caseCIMGraticule:vargridGraticule=girdGraticuleObjectasCIMGraticule;gridGraticule.Name=symbolItemName;gridGraticule.SetGeographicCoordinateSystem(mapFrame.Map.SpatialReference);//assign grid to the frame mapGrids.Add(gridGraticule);break;caseCIMMeasuredGrid:vargridMeasure=girdGraticuleObjectasCIMMeasuredGrid;gridMeasure.Name=symbolItemName;gridMeasure.SetProjectedCoordinateSystem(mapFrame.Map.SpatialReference);//assign grid to the framemapGrids.Add(gridMeasure);break;caseCIMReferenceGrid:vargridReference=girdGraticuleObjectasCIMReferenceGrid;gridReference.Name=symbolItemName;//assign grid to the framemapGrids.Add(gridReference);break;}cmf.Grids=mapGrids.ToArray();mapFrame.SetDefinition(cmf);
Apply a style to a Graphic Element
//Note: Run within QueuedTask context.//Get the Style project items in the projectvarstyleProjectItems=Project.Current?.GetItems<StyleProjectItem>();//Get the ArcGIS 2D Style Project ItemvarstyleProjectItem=styleProjectItems.OfType<StyleProjectItem>().FirstOrDefault(s =>s.Name=="ArcGIS 2D");if(styleProjectItem==null)return;//Get the north arrow style item you needvarpointStyleItem=styleProjectItem.SearchSymbols(StyleItemType.PointSymbol,"Circle 3").FirstOrDefault();if(pointStyleItem==null)return;//Select a North arrow layout elementvarlayoutPointElement=layout.GetSelectedElements().FirstOrDefault();if(layoutPointElement!=null&&layoutPointElementisGraphicElementge){if(layoutPointElement.CanApplyStyle(pointStyleItem)){//The magic happens here//for Graphic Elements such as Point, Lines, Polys, text, preserve size. ge.ApplyStyle(pointStyleItem,true);}}
// sets only the Guide snapping mode ArcGIS.Desktop.Layouts.LayoutSnapping.SetSnapModes(new[]{LayoutSnapMode.Guide});// sets only Element and Page snapping modesArcGIS.Desktop.Layouts.LayoutSnapping.SetSnapModes(new[]{LayoutSnapMode.Element,LayoutSnapMode.Page});// clear all snap modesArcGIS.Desktop.Layouts.LayoutSnapping.SetSnapModes(null);// set snap modes one at a timeArcGIS.Desktop.Layouts.LayoutSnapping.SetSnapMode(LayoutSnapMode.Margins,true);ArcGIS.Desktop.Layouts.LayoutSnapping.SetSnapMode(LayoutSnapMode.Guide,true);/// LayoutSnapping.SetSnapModes(new[]{ LayoutSnapMode.Guide }); // sets only the Guide snapping mode // get current snap modesvarsnapModes=ArcGIS.Desktop.Layouts.LayoutSnapping.SnapModes;// get state of a specific snap modeboolisOn=ArcGIS.Desktop.Layouts.LayoutSnapping.GetSnapMode(LayoutSnapMode.Guide);
Layout Metadata
Layout Metadata
//Note: Must be on QueuedTask.Run//Gets the Layout metadata.varlayout_xml=layout.GetMetadata();//Can metadata be edited?if(layout.GetCanEditMetadata())//Set the metadata backlayout.SetMetadata(layout_xml);
Layout MapFrame
Change the map associated with a map frame
//Change the map associated with a map frame//Find a map frame element from a layout by the map frame's element nameMapFramemfrm=layout.FindElement("Map Frame")asMapFrame;//Note: Must be on QueuedTask.Run//Reference map from the project item MapmyMap=Project.Current.GetItems<MapProjectItem>().FirstOrDefault(m =>m.Name.Equals("Map1")).GetMap();//Set the map to the map framemfrm.SetMap(map);
Change map frame camera settings
//Change a map frame's camera settings.//Reference MapFrameMapFramemf=layout.FindElement("Map Frame")asMapFrame;//Reference the camera associated with the map frame and change the scaleCameracam=mf.Camera;cam.Scale=100000;//Set the map frame extent based on the new camera infomf.SetCamera(cam);
Zoom map frame to extent of a single layer
//Zoom map frame to the extent of a single layer.//Note: Must be on QueuedTask.Run//Reference map and layerMapm=mapFrame.Map;FeatureLayerlyr=m.FindLayers("GreatLakes").First()asFeatureLayer;//Set the map frame extent to all features in the layermapFrame.SetCamera(lyr,false);
Change map frame extent to selected features in multiple layers
//Change the extent of a map frame to the selected features multiple layers.//Note: Must be on QueuedTask.Run//Reference MapFrame//Reference map, layers and create layer listMapm=mapFrame.Map;FeatureLayerfl_1=m.FindLayers("GreatLakes").First()asFeatureLayer;FeatureLayerfl_2=m.FindLayers("States_WithRegions").First()asFeatureLayer;varlayers=new[]{fl_1,fl_2};//IEnumerable<Layer> layers = m.Layers; //This creates a list of ALL layers in map.//Set the map frame extent to the selected features in the list of layersmapFrame.SetCamera(layers,true);
Change map frame extent to single feature with 15 percent buffer
//Change map frame extent to single feature with 10 percent buffer//Note: Must be on QueuedTask.Run//Reference the mapframe and its associated mapMapm=mapFrame.Map;//Reference a feature layer and build a query (to return a single feature)FeatureLayerfl=m.FindLayers("GreatLakes").First()asFeatureLayer;QueryFilterqf=newQueryFilter();stringwhereClause="NAME = 'Lake Erie'";qf.WhereClause=whereClause;//Zoom to the featureusing(ArcGIS.Core.Data.RowCursorrowCursor=fl.Search(qf)){while(rowCursor.MoveNext()){//Get the shape from the row and set extentusing(varfeature=rowCursor.CurrentasArcGIS.Core.Data.Feature){Polygonpolygon=feature.GetShape()asPolygon;Envelopeenv=polygon.ExtentasEnvelope;mapFrame.SetCamera(env);//Zoom out 15 percentCameracam=mapFrame.Camera;cam.Scale=cam.Scale*1.15;mapFrame.SetCamera(cam);}}}
Activate Map Frame
//We can activate a map frame on the layout of the active viewvarmap_frame=layout.GetElementsAsFlattenedList().OfType<MapFrame>().FirstOrDefault(mf =>mf.Name=="Map 1");if(map_frame==null)return;//can we activate the map frame?if(layoutView.CanActivateMapFrame(map_frame))//activate it - Note: we are on the UI thread!layoutView.ActivateMapFrame(map_frame);
Deactivate Map Frame
//Deactivate any activated map frame//Note: we are on the UI thread!layoutView.DeactivateMapFrame();//no-op if nothing activated//or - check if a map frame is activated first...if(layoutView.ActivatedMapFrame!=null)//Note: we are on the UI thread!layoutView.DeactivateMapFrame();
Get the Activated Map Frame and MapView
//The active view must be a layout view.varlv=LayoutView.Active;if(lv==null)return;varmap_view=lv.ActivatedMapView;if(map_view!=null){//TODO - use activated map view}varmap_frame=lv.ActivatedMapFrame;if(map_frame!=null){//TODO - use activated map frame}
Translates a point in page coordinates to a point in map coordinates.
varpointSymbol=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.BlackRGB,8);vargraphicsLayer=MapView.Active.Map.GetLayersAsFlattenedList().OfType<GraphicsLayer>().FirstOrDefault();//Note: Must be on QueuedTask.Run//Get a point in the center of the Map framevarmapFrameCenterPoint=mapFrame.GetBounds().CenterCoordinate;//Convert to MapPointvarpointInMapFrame=MapPointBuilderEx.CreateMapPoint(mapFrameCenterPoint);//Find the corresponding point in the MapViewvarpointOnMap=mapFrame.PageToMap(pointInMapFrame);//Create a point graphic on the MapView.varcimGraphicElement=newCIMPointGraphic{Location=pointOnMap,Symbol=pointSymbol.MakeSymbolReference()};graphicsLayer.AddElement(cimGraphicElement);
Translates a point in map coordinates to a point in page coordinates
//Note: Must be on QueuedTask.RunvarpointSymbol=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.BlackRGB,8);//Convert the clicked point in client coordinates to the corresponding map coordinates.//clicked point can be from a Map Tool's HandleMouseDownAsync callback.//MapViewMouseButtonEventArgs ClientPoint property.PointclickedPoint;varclickedMapPoint=MapView.Active.ClientToMap(clickedPoint);ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(string.Format("X: {0} Y: {1} Z: {2}",mapPoint.X,mapPoint.Y,mapPoint.Z),"Map Coordinates");//Get the corresponding layout pointvarpointOnLayoutFrame=mapFrame.MapToPage(mapPoint);//Create a point graphic on the Layout.varcimGraphicElement=newCIMPointGraphic{Location=pointOnLayoutFrame,Symbol=pointSymbol.MakeSymbolReference()};//Or use GraphicFactoryvarcimGraphicElement2=GraphicFactory.Instance.CreateSimpleGraphic(pointOnLayoutFrame,pointSymbol);ElementFactory.Instance.CreateGraphicElement(layout,cimGraphicElement);ElementFactory.Instance.CreateGraphicElement(layout,cimGraphicElement2);
Layout MapSeries
Modify an existing map series
//Modify the currently active map series and changes its sort field and page number field.//Note: Must be on QueuedTask.RunSpatialMapSeriesSMS=layout.MapSeriesasSpatialMapSeries;//cast as spatial map series for additional membersSMS.SortField="State_Name";SMS.SortAscending=true;SMS.PageNumberField="PageNum";//Overwrite the current map series with these new settingslayout.SetMapSeries(SMS);
Create a new spatial map series
// This example create a new spatial map series and then applies it to the active layout. This will automatically // overwrite an existing map series if one is already present.//Note: Must be on QueuedTask.Run;//SpatialMapSeries constructor - required parametersBasicFeatureLayerindexLyr=map.FindLayers("Countries").FirstOrDefault()asBasicFeatureLayer;SpatialMapSeriesSMS=MapSeries.CreateSpatialMapSeries(layout,mapFrame,indexLyr,"Name");//Set optional, non-default valuesSMS.CategoryField="Continent";SMS.SortField="Population";SMS.ExtentOptions=ExtentFitType.BestFit;SMS.MarginType=ArcGIS.Core.CIM.UnitType.PageUnits;SMS.MarginUnits=ArcGIS.Core.Geometry.LinearUnit.Centimeters;SMS.Margin=1;SMS.ScaleRounding=1000;layout.SetMapSeries(SMS);//Overwrite existing map series.
Layout Export
Export a layout to PDF
//Export a single page layout to PDF.//Create a PDF format with appropriate settings//BMP, EMF, EPS, GIF, JPEG, PNG, SVG, TGA, and TFF formats are also available for exportstringfilePath=@"Path and file name for the output export file";PDFFormatPDF=newPDFFormat(){OutputFileName=filePath,Resolution=300,DoCompressVectorGraphics=true,DoEmbedFonts=true,HasGeoRefInfo=true,ImageCompression=ImageCompression.Adaptive,ImageQuality=ImageQuality.Best,LayersAndAttributes=LayersAndAttributes.LayersAndAttributes};//Check to see if the path is valid and exportif(PDF.ValidateOutputFilePath()){//Note: Must be on QueuedTask.Runlayout.Export(PDF);//Export the layout to PDF on the worker thread}
Export a map frame to JPG
//Export a map frame to JPG.stringfilePath=@"Path and file name for the output export file";//Create JPEG format with appropriate settings//BMP, EMF, EPS, GIF, PDF, PNG, SVG, TGA, and TFF formats are also available for exportJPEGFormatJPG=newJPEGFormat(){HasWorldFile=true,Resolution=300,OutputFileName=filePath,ColorMode=JPEGColorMode.TwentyFourBitTrueColor,Height=800,Width=1200};//Reference the map frameMapFramemf=layout.FindElement("MyMapFrame")asMapFrame;//Export on the worker thread//Note: Must be on QueuesTask.Run//Check to see if the path is valid and exportif(JPG.ValidateOutputFilePath()){mf.Export(JPG);//Export the map frame to JPG}
Export the map view associated with a map frame to BMP
//Export the map view associated with a map frame to BMP.stringfilePath=@"Path and file name for the output export file";//Create BMP format with appropriate settings//EMF, EPS, GIF, JPEG, PDF, PNG, SVG, TGA, and TFF formats are also available for exportBMPFormatBMP=newBMPFormat(){Resolution=300,Height=500,Width=800,HasWorldFile=true,OutputFileName=filePath};//Export on the worker threadawaitQueuedTask.Run(()=>{MapViewmv_bmp=mapFrame.GetMapView(layoutView);if(mv_bmp!=null){//Check to see if the path is valid and exportif(BMP.ValidateOutputFilePath()){mv_bmp.Export(BMP);//Export to BMP}}});
Export a map series to single PDF
//Export a map series with multiple pages to a single PDF.stringfilePath=@"Path and file name for the output export file";//Create PDF format with appropriate settingsPDFFormatMS_PDF=newPDFFormat(){OutputFileName=filePath,Resolution=300,DoCompressVectorGraphics=true,DoEmbedFonts=true,HasGeoRefInfo=true,ImageCompression=ImageCompression.Adaptive,ImageQuality=ImageQuality.Best,LayersAndAttributes=LayersAndAttributes.LayersAndAttributes};//Set up map series export optionsMapSeriesExportOptionsMS_ExportOptions=newMapSeriesExportOptions(){ExportPages=ExportPages.Custom,//Provide a specific list of pagesCustomPages="1-3, 5",//Only used if ExportPages.Custom is setExportFileOptions=ExportFileOptions.ExportAsSinglePDF,//Export all pages to a single, multi-page PDFShowSelectedSymbology=false//Do no show selection symbology in the output};//Export on the worker thread//Note: Must be on QueuedTask.Run//Check to see if the path is valid and exportif(MS_PDF.ValidateOutputFilePath()){layout.Export(MS_PDF,MS_ExportOptions);//Export to PDF}
Export a map series to individual TIFF files
//Export each page of a map series to an individual TIFF file.stringfilePath=@"Path and file name for the output export file";//Create TIFF format with appropriate settingsTIFFFormatTIFF=newTIFFFormat(){OutputFileName=filePath,Resolution=300,ColorMode=TIFFColorMode.TwentyFourBitTrueColor,HasGeoTiffTags=true,HasWorldFile=true,ImageCompression=TIFFImageCompression.LZW};//Set up map series export optionsMapSeriesExportOptionsMSExportOptions_TIFF=newMapSeriesExportOptions(){ExportPages=ExportPages.All,//All pagesExportFileOptions=ExportFileOptions.ExportMultipleNames,//Export each page to an individual file using page name as a suffix.ShowSelectedSymbology=true//Include selection symbology in the output};//Export on the worker thread//Note: Must be on the QueuedTask.Run()//Check to see if the path is valid and exportif(TIFF.ValidateOutputFilePath()){layout.Export(TIFF,MSExportOptions_TIFF);//Export to TIFF}
LayoutOptions
Get LayoutOptions
varlastToolActive=ApplicationOptions.LayoutOptions.KeepLastToolActive;varwarnOnSurrounds=ApplicationOptions.LayoutOptions.WarnAboutAssociatedSurrounds;//eg <Install_Path>\Resources\LayoutTemplates\en-USvargallery_path=ApplicationOptions.LayoutOptions.LayoutTemplatePath;vardefaultGuideColor=ApplicationOptions.LayoutOptions.DefaultGuideColor;//Note: Must be on QueuedTask.Run.varguideColor=ApplicationOptions.LayoutOptions.GetGuideColor();
Set LayoutOptions
//keep graphic element insert tool activeApplicationOptions.LayoutOptions.KeepLastToolActive=true;//no warning when deleting a map frame results in other elements being deletedApplicationOptions.LayoutOptions.WarnAboutAssociatedSurrounds=false;//path to .pagx files used as templatesApplicationOptions.LayoutOptions.LayoutTemplatePath=@"D:\data\layout_templates";varguideColor=ApplicationOptions.LayoutOptions.GetGuideColor();// set guide color//Note: Must be on QueuedTask.RunApplicationOptions.LayoutOptions.SetGuideColor(ColorFactory.Instance.RedRGB);
TextAndGraphicsElementsOptions
Get All Available Fonts
//Note: see also SymbolFactory.Instance.GetAvailableFonts() which returns the//same list. Use for TextAndGraphicsElementsOptions.GetAvailableFonts() convenience//A list of tuples of Font name + associated Font Styles, one tuple per//font, is returned//Note: Must be on QueuedTask.Runvarfonts=ApplicationOptions.TextAndGraphicsElementsOptions.GetAvailableFonts();StringBuildersb=newStringBuilder();sb.AppendLine("Pro Fonts\r\n============================");foreach(varfontinfonts){varstyles=string.Join(",",font.fontStyles);sb.AppendLine($"{font.fontName}, [{styles}]");}System.Diagnostics.Debug.WriteLine(sb.ToString());
Get TextAndGraphicsElementsOptions
//Note: Must be on QueuedTask.Run//Get the default font (see also 'SymbolFactory.Instance.DefaultFont')vardef_font=ApplicationOptions.TextAndGraphicsElementsOptions.GetDefaultFont();System.Diagnostics.Debug.WriteLine($"\r\ndefault font: {def_font.fontName}, {def_font.styleName}");//Get the default graphics element symbols - point, line, poly, textvarptSymbol=ApplicationOptions.TextAndGraphicsElementsOptions.GetDefaultPointSymbol();varlineSymbol=ApplicationOptions.TextAndGraphicsElementsOptions.GetDefaultLineSymbol();varpolySymbol=ApplicationOptions.TextAndGraphicsElementsOptions.GetDefaultPolygonSymbol();vartextSymbol=ApplicationOptions.TextAndGraphicsElementsOptions.GetDefaultTextSymbol();
Set TextAndGraphicsElementsOptions
//Note: Must be on QueuedTask.Run//Set a default font. Use its default styleApplicationOptions.TextAndGraphicsElementsOptions.SetDefaultFont("tahoma");//or specify an explicit styleApplicationOptions.TextAndGraphicsElementsOptions.SetDefaultFont("tahoma","bold");//Create symbolsvarptSymbol2=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB,14,SimpleMarkerStyle.Diamond);varlineSymbol2=SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.RedRGB,2,SimpleLineStyle.Dash);varpolySymbol2=SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB,SimpleFillStyle.DiagonalCross);vartextSymbol2=SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.RedRGB,12);//Set default point, line, poly, text graphics element symbolsApplicationOptions.TextAndGraphicsElementsOptions.SetDefaultPointSymbol(ptSymbol2);ApplicationOptions.TextAndGraphicsElementsOptions.SetDefaultLineSymbol(lineSymbol2);ApplicationOptions.TextAndGraphicsElementsOptions.SetDefaultPolygonSymbol(polySymbol2);ApplicationOptions.TextAndGraphicsElementsOptions.SetDefaultTextSymbol(textSymbol2);
MapFrame_Display_Constraints
SetAutoCameraNone
//Note: Must be on QueuedTask.RunvarautoCamera=mapFrame.GetAutoCamera();autoCamera.Source=AutoCameraSource.None;if(mapFrame.ValidateAutoCamera(autoCamera)&&!mapFrame.IsMapSeriesMapFrame())mapFrame.SetAutoCamera(autoCamera);