Presentation is loading. Please wait.

Presentation is loading. Please wait.

Symbolizing elements and layers(I)

Similar presentations


Presentation on theme: "Symbolizing elements and layers(I)"— Presentation transcript:

1 Symbolizing elements and layers(I)
Introduction to Programming ArcObjects with VBA

2 Lesson overview 总体介绍符号化对象(symbology objects) 为地图添加一个简单的图形(graphics)
符号对象Symbol objects 颜色对象Color objects 颜色梯度对象Color ramps 为地图添加一个简单的图形(graphics) 使用特征渲染对象修改图层显示方式(FeatureRenderers) 使用图层文件(*.lyr)来管理图层的符号化 Overview This lesson will introduce you to some of the ArcObjects required to control how elements (“graphics”) and layers are displayed on the map. Symbol—There are several creatable subtypes of Symbol, including text symbols, line symbols, and fill symbols, for example. Color—The (abstract) Color class has five creatable subtypes, allowing the programmer to define colors in a variety of ways. ColorRamp—ArcGIS has four creatable color ramps that a programmer can use to build a collection of colors. FeatureRenderer—FeatureRenderers control how data in a feature layer are categorized and symbolized. This section will discuss some of the more common types of renderers. You will learn how to programmatically create, modify, and add graphic elements to the map or page layout. You will also learn how to manage layer symbology by saving and retrieving layer files from disk. Introduction to Programming ArcObjects with VBA

3 Symbol类的子类 * Symbol You will find the Symbol abstract class and all of its subtypes listed on the Display object model diagram. Any item on the Map or PageLayout must have a symbol in order to be displayed. ArcMap uses MarkerSymbols, LineSymbols, or FillSymbols to display geometry, and TextSymbols to display text elements. There are also 3DChartSymbols for drawing charts (graphs). The ISymbol interface (supported by each subtype of Symbol) has methods for drawing a symbol directly to a device context (DC). A device context is basically a window display, such as the ArcMap display, an ArcCatalog preview pane, or a (standalone Visual Basic) user form. Each symbol subclass has methods and properties a programmer can use to define the symbol, such as Style, Line Width, Font, Size, Angle, and Color. Choose the appropriate subclass of symbol according to how you would like to define it: a PictureMarkerSymbol to define a marker from a bitmap or GIF image, a CharacterMaker to define a marker from a specific font and character, for example. Example: Creating a simple (dashed) line symbol Dim pSLineSymbol As ISimpleLineSymbol Set pSLineSymbol = New SimpleLineSymbol pSLineSymbol.Style = esriSLSDash 'esriSimpleLineStyle Example: Creating a simple (diagonal-hatched) fill symbol Dim pSFillSymbol As ISimpleFillSymbol Set pSFillSymbol = New SimpleFillSymbol pSFillSymbol.Style = esriSFSForwardDiagonal 'esriSimpleFillStyle * Several additional types of symbols are listed on the Display OMD, including TextSymbols Introduction to Programming ArcObjects with VBA

4 使用color对象 以下五种可创建的对象 用来定义颜色对象的属性 使用Color对象来访问一个Symbol对象的Color属性
RgbColor(红、绿、蓝) CmykColor(青、洋红、黄、黑) HsvColor(色调、饱和度、值) HlsColor(色调、亮度、饱和度) GrayColor(灰度) 用来定义颜色对象的属性 Red, Green, Blue values (0–255) 灰度 (0=white – 255=black) Cyan, Magenta, Yellow, Black 使用Color对象来访问一个Symbol对象的Color属性 Add some color to your code Because the five subclasses of color are coclasses, they can each be created with the New keyword. As a programmer, you can choose Color objects and interfaces according to how you would like to define a particular color. To specify individual values for red, green, and blue for example, you would use the IRgbColor interface on the RgbColor class. Below are brief descriptions of how color is defined for each of the five color interfaces. IRgbColor: Red, green, and blue (0–255) ICmykColor: Cyan, magenta, yellow, and black (0–255) IHsvColor: Hue (0–360), saturation, and value (0–100) IHlsColor: Hue, lightness, and saturation (0–100) IGrayColor: Level 0 (white) to 255 (black) Visual Basic functions for defining color Visual Basic has some built in ways to specify color values. One of the most powerful is the RGB function. The RGB function takes three integer arguments that indicate the amount of red, green, and blue respectively. Here’s an example of using the RGB function to make a cyan color: Dim myColor As IRGBColor Set myColor = New RGBColor myColor.RGB = RGB(0,255,255) '*Red,Green,Blue: 0-255 Visual Basic also contains color constants that can be used to define a handful of basic colors. These constants are: vbBlack, vbBlue, vbCyan, vbGreen, vbMagenta, vbRed, vbWhite, and vbYellow Introduction to Programming ArcObjects with VBA

5 颜色梯度对象ColorRamps 四种可以创建的对象 Algorithmic ColorRamp(算法颜色梯度)
Random ColorRamp(随机颜色梯度) Preset ColorRamp(预定义颜色梯度) MultiPart ColorRamp(多部分的颜色梯度) Color ramps The four subclasses of ColorRamp are coclasses. Therefore, the programmer can create them with the New keyword. After instantiating a ColorRamp object, the number of colors are specified by setting the Size property; the ramp is then created by calling the CreateRamp method. Once the ramp is produced, an enumeration of the colors can be retrieved from the Ramp object by using the Colors property. Choose the ramp appropriate for how you need the colors defined. Example: Create a new random color ramp Public Function GetRandomRamp (NumColors As Integer) As IEnumColors Dim pRandomColorRamp As IColorRamp Set pRandomColorRamp = New RandomColorRamp pRandomColorRamp.Size = NumColors ' *Passed into the function Dim blnOK As Boolean pRandomColorRamp.CreateRamp blnOK '* Make it so! If Not blnOK Then Exit Function '* Exit if there was an error Set GetRandomRamp = pRandomColorRamp '*Pass back the ramp End Function Introduction to Programming ArcObjects with VBA

6 创建一个新的 Randomcolorramp对象
Public Function GetRandomRamp (NumColors As Integer) As IEnumColors Dim pRandomColorRamp As IColorRamp Set pRandomColorRamp = New RandomColorRamp pRandomColorRamp.Size = NumColors ' *Passed into the function Dim blnOK As Boolean pRandomColorRamp.CreateRamp blnOK '* Make it so! If Not blnOK Then Exit Function '* Exit if there was an error Set GetRandomRamp = pRandomColorRamp '*Pass back the ramp End Function RandomColorRamp.CreateRamp方法返回的是IEnumColors对象。是一个枚举对象。

7 创建简单的图形元素( graphic elements)
有一些可以创建的对象 图形元素的种类 Line, polygon, marker Text and pictures 框架元素(FrameElements ) 在PageLayout上使用 Map frames North arrows, legends, scale bars Table frames Elements There are two broad types of element: GraphicElement and FrameElement. GraphicElements are “dumb” elements that once added to the display, will not change unless the user does so explicitly. Graphic elements are things like simple shapes (markers, lines, polygons), text strings, or images (such as a company logo). FrameElements, on the other hand, are elements that contain objects, such as tables, maps, or map surrounds. Map surrounds are map-related elements added to the PageLayout that will dynamically change to reflect changes in an associated map. A scalebar, for example, after being added to the layout, will change to reflect the current map scale as the user zooms in and out on the display. In this section, you will learn the basics of working with graphic elements. In a later section, you will learn more about adding frame elements to the page layout. Introduction to Programming ArcObjects with VBA

8 例子: 创建一个新的图形元素并设置它的符号
Dim pMarkerElem As IMarkerElement Set pMarkerElem = New MarkerElement ‘创建一个新的元素 Dim pMarkerSym As ISimpleMarkerSymbol Set pMarkerSym = New SimpleMarkerSymbol ‘创建新符号 pMarkerSym.Style = esriSMSCircle ‘指定符号的风格 Dim pColor As IRgbColor Set pColor = New RgbColor ‘创建一个新颜色 pColor.RGB = RGB(255,0,0) ‘设置成红色 pMarkerSym.Color = pColor ‘把颜色赋给符号 pMarkerElem.Symbol = pMarkerSym ‘ 把符号赋给元素 The color’s connected to the … sym-bol. The symbol’s connected to the … mar-ker. Follow the same general process illustrated in the example above for any graphic element you want to create. Create a new graphic element (LineElement, MarkerElement, PolygonElement, TextElement, etc.). Create a new symbol appropriate for the element (LineSymbol, TextSymbol, FillSymbol, etc.). Create a new color object (RgbColor, CmykColor, GrayColor, HlsColor, or HsvColor). Define the color’s value. Assign the color to the symbol. Define the symbol’s style. Assign the symbol to the graphic element. At this point, the graphic element is completely defined, but does not yet appear on the display. Introduction to Programming ArcObjects with VBA

9 定义一个元素的位置 使用IElement 的 Geometry属性 被所有Element的子类所支持
在地图(Map)或布局 (layout page)上定位 定位可以指定为 point, line, envelope等 Dim pElem As IElement Set pElem = pMarkerElem 'QI Dim pPoint As IPoint Set pPoint = New Point pPoint.PutCoords , pElem.Geometry = pPoint Tell that element where to go All elements support a Geometry property (defined on the IElement interface). Before adding any element to the display (GraphicsContainer), you must first define where the element is to appear on the page or map. An element’s Geometry property can be specified with either a point, a line, or an envelope, depending on which is most appropriate. Marker elements, of course, should be defined using a point. Text elements, on the other hand, can be positioned with a point (the center of the text), a line (perhaps a curve that the text should follow), or an envelope (bounding box). Geometry can be defined either in page units (for elements added to the page layout) or in map units (for elements added to the data frame). 沿线标注文本类型的Element的定位就可以是Line对象 Introduction to Programming ArcObjects with VBA

10 把一个元素添加到 map (或者 layout)
使用 IGraphicsContainer :: AddElement 指定添加的元素和它的序号 0号的序号是第一个(最顶部)的元素,序号从顶到底逐渐增加 Dim pMxDoc As IMxDocument Set pMxDoc = ThisDocument pMxDoc.ActiveView.GraphicsContainer.AddElement pElem, 0 ‘或者使用以下语句 Dim pGContainer As IGraphicsContainer Set pGContainer = pMxDoc.FocusMap ‘QI pGContainer.AddElement pElem, '0=top element pMxDoc.ActiveView.Refresh Adding an element to the graphics container Both the Map and PageLayout classes support the IGraphicsContainer interface. As the name implies, this is an interface that allows a programmer to manage graphic elements that appear either in the data frame or in the page layout. The AddElement method is used to place new elements on the display in a given order (e.g., on top of all other elements). To add an element to the layout, use IGraphicsContainer on the PageLayout object and make sure your element’s position (Geometry property) has been defined in page units. An element added to the data frame should use IGraphicsContainer on the Map object, and have its geometry defined in map units. In one aspect, the GraphicsContainer is like a list. The elements inside the container have an order; elements at the beginning (position 0) display on top of subsequently listed elements. To control which elements are drawn on top of others, a programmer can change the order of elements using methods such as SendToBack, BringToFront, or PutElementOrder. When retrieving elements, the GraphicsContainer behaves like an enum. To retrieve elements from the container, a programmer cannot use the element’s position, but must instead use the Next method to pull out elements sequentially, and the Reset method to move the pointer back to the top. 通过刷新屏幕来显示新添加的元素 Introduction to Programming ArcObjects with VBA

11 FeatureRenderers对象 Renderers 方法定义了 layer 对象是怎么显示的
All feature layers have an associated FeatureRenderer that can be set or returned through the Renderer property, which is defined on the IGeoFeatureLayer interface. The Renderer property is a property put by reference, so you must use the Set keyword when assigning an object to this property. There are several subtypes of FeatureRenderers, each of which is a coclass, and can therefore be created with the New keyword. In this lesson, you will be introduced to the common renderers listed below. SimpleRenderer ArcMap software’s default feature renderer. A SimpleRenderer symbolizes every feature in the layer with the same symbology (i.e., style and color). UniqueValueRenderer Displays a layer by assigning a different symbol to each unique value found in a given attribute field. A land cover map, for example, could be displayed with a UniqueValueRenderer to show a handful of unique land cover types that may exist for several thousand polygons. ClassBreaksRenderer Uses a classification based on one of the layer’s numeric attributes to display statistically (or manually) defined groups of features. The class boundaries may be set explicitly or by using one of the ArcMap Classify objects (NaturalBreaks, DefinedInterval, Quantile, EqualInterval, or StandardDeviation). ScaleDependentRenderer A renderer that actually contains a collection of renderers. Its purpose is to let you specify different renderers for particular scale ranges. You might use more detailed symbols as your user zooms in and more general symbology when he or she zooms out, for example. 其它的Renderers对象可以用来显示 RasterLayers 和 TinLayers Introduction to Programming ArcObjects with VBA

12 简单渲染SimpleRenderer 默认的使用简单的符号来渲染显示要素 属性 在修来了图层的渲染方式之后需要执行刷新操作
Symbol: 颜色和风格 Label: 在 legend中显示的字符串 在修来了图层的渲染方式之后需要执行刷新操作 USA Example: Create and modify a SimpleRenderer Private Sub ApplySimpleRenderer(SomeLayer As IGeoFeatureLayer) Dim pSRenderer As ISimpleRenderer Set pSRenderer = New SimpleRenderer Dim pFillSymbol As ISimpleFillSymbol Set pFillSymbol = New SimpleFillSymbol pFillSymbol.Style = esriSFSForwardDiagonal Dim pColor As IRgbColor Set pColor = New RgbColor pColor.RGB = vbBlue pFillSymbol.Color = pColor 'Property put by reference, must use "Set" … Set pSRenderer.Symbol = pFillSymbol pSRenderer.Label = "USA" 'Set the layer’s renderer, also property put by reference Set SomeLayer.Renderer = pSRenderer Dim pMxDoc As IMxDocument Set pMxDoc = ThisDocument pMxDoc.UpdateContents 'Update legend pMxDoc.ActiveView.Refresh 'Redraw display End Sub ‘设置一个要素类图层的渲染对象 Set pFLayer.Renderer = pRender ‘刷新显示 pMxDoc.ActiveView.Refresh ‘刷新内容表(TOC)显示新的图标 pMxDoc.UpdateContents Introduction to Programming ArcObjects with VBA

13 唯一值渲染UniqueValueRenderer
根据不同的唯一值用一个符号来显示要素 属性 Field(s): 提供唯一分类值的字段 Value(s):特征的唯一分类值 ValueCount: 需要显示的唯一分类值的数目 Example: Create a UniqueValueRenderer to uniquely symbolize each state Private Sub ApplyUniqueRenderer(SomeLayer As IGeoFeatureLayer) Dim pUVRenderer As IUniqueValueRenderer Set pUVRenderer = New UniqueValueRenderer Dim pColorEnum As IEnumColors Set pColorEnum = MakeRandomRamp(50) 'Example on pg 12-5 pUVRenderer.FieldCount = 1 pUVRenderer.Field(0) = "STATE_NAME" Dim pFClass As IFeatureClass Set pFClass = SomeLayer.FeatureClass Dim pFCursor As IFeatureCursor Set pFCursor = pFClass.Search(Nothing, False) Dim pFeature As IFeature, pSym As ISimpleFillSymbol Set pFeature = pFCursor.NextFeature Do Until pFeature Is Nothing Set pSym = New SimpleFillSymbol pSym.Color = pColorEnum.Next pUVRenderer.AddValue _ pFeature.Value(pFClass.FindField("STATE_NAME")), "States", pSym Loop Set SomeLayer.Renderer = pUVRenderer 'Property put by reference m_pMxDoc.UpdateContents m_pMxDoc.ActiveView.Refresh End Sub Introduction to Programming ArcObjects with VBA

14 例子: 创建一个 唯一值专题图为每个州赋一个符号
Private Sub ApplyUniqueRenderer(SomeLayer As IGeoFeatureLayer) Dim pUVRenderer As IUniqueValueRenderer Set pUVRenderer = New UniqueValueRenderer Dim pColorEnum As IEnumColors Set pColorEnum = MakeRandomRamp(50) pUVRenderer.FieldCount = 1 pUVRenderer.Field(0) = "STATE_NAME" Dim pFClass As IFeatureClass Set pFClass = SomeLayer.FeatureClass Dim pFCursor As IFeatureCursor Set pFCursor = pFClass.Search(Nothing, False) Dim pFeature As IFeature, pSym As ISimpleFillSymbol Set pFeature = pFCursor.NextFeature Do Until pFeature Is Nothing Set pSym = New SimpleFillSymbol pSym.Color = pColorEnum.Next pUVRenderer.AddValue _ pFeature.Value(pFClass.FindField("STATE_NAME")), "States", pSym Loop Set SomeLayer.Renderer = pUVRenderer m_pMxDoc.UpdateContents m_pMxDoc.ActiveView.Refresh End Sub

15 分类端点渲染ClassBreaksRenderer
根据数字字段的值分组,每一个分组使用一个符号 属性 Breaks: 分组的分界点 Field: 提供属性分组的数字型字段 BreakCount: 所有分组的数目 分类的方法 使用列表在OMD图表中适当的 Classify 对象 Those are the Breaks A ClassBreaksRenderer is used to display classes of a layer’s features based on a numeric attribute. When creating a ClassBreaksRenderer, you need to specify the number of classes to use, the field on which the classification is based and whether classes should be sorted lowest to highest (ascending) or highest to lowest (descending). The breaks (cut-off points) that define each class also need to be explicitly defined by the programmer, along with the symbol that will be used to symbolize each class. The numeric values that represent the break points for each class can be defined arbitrarily (hard-coded) or may be derived from a statistical method. Assigning classes and symbols to the renderer is usually performed in a looping routine such as the pseudocode shown below. For i=0 to the-number-of-classes -1 Make a new symbol Set symbol properties (e.g., color) Assign class break i Assign the symbol for class i Next i Introduction to Programming ArcObjects with VBA

16 把图层文件保存到磁盘上 可以把图层 保存成图层文件(*.lyr) 图层文件保存了Layer对象的以下信息 Layer的数据源的路径
符号化的方法 Label 的方式 所定义的查询 等等 Layer files In ArcGIS, a layer object can live in one of two places: saved as part of an ArcMap document (*.mxd, *.mxt) or saved individually in a layer file (*.lyr). In either case, the layer will define the path to a data source (e.g., shapefile) and options for data display (classification, symbology, labels, etc.). By storing layers in layer files, display properties only need to be set once. Layers that are used frequently can be easily reused between documents without having to redefine display options inside ArcMap. Layer files are especially well suited for base layers that are used in several maps and may also require a consistent (standard) symbology. Introduction to Programming ArcObjects with VBA

17 Example: 在ArcMap中保存一个图层文件
Public Sub SaveFirstLayer () Dim pMxDoc As IMxDocument Set pMxDoc = ThisDocument ‘创建一个新的 GxLayer对象 Dim pGxLayer As IGxLayer Set pGxLayer = New GxLayer ‘是一个Coclass可以使用New创建 ‘通过QI取得IGFile接口 Dim pGxFile As IGxFile Set pGxFile = pGxLayer ‘定义文件路径 pGxFile.Path = "C:\Data\Shelbyville.lyr" ‘连接一个Layer对象 Set pGxLayer.Layer = pMxDoc.FocusMap.Layer(0) ‘保存文件 pGxFile.Save ‘完成! End Sub Programmatically saving layer files The GxLayer class is a coclass, so instances can be created using the New keyword. The only member available on the IGxLayer interface is the Layer property. IGxLayer:: Layer is used to define or retrieve the layer object stored in the file. GxLayer is a subclass of GxFile, and therefore supports the IGxFile interface. When saving a new layer file, you must QueryInterface to IGxFile in order to define the output file name (using the Path property). The Save method must be called to commit the layer file to disk. Example: Saving all layers in the active data frame Public Sub SaveAllLayers () Dim pMxDoc As IMxDocument Set pMxDoc = ThisDocument Dim pEnumLayer As IEnumLayer, pLayer As ILayer Set pEnumLayer = pMxDoc.FocusMap.Layers Set pLayer = pEnumLayer.Next Do Until pLayer Is Nothing Dim pGxLayer As IGxLayer Dim pGxFile As IGxFile Set pGxLayer = New GxLayer Set pGxFile = pGxLayer '**QueryInterface pGxFile.Path = "C:\Data\Layers\" & pLayer.Name & ".lyr" Set pGxLayer.Layer = pLayer pGxFile.Save Loop End Sub Introduction to Programming ArcObjects with VBA

18 Using tools(II) Introduction to Programming ArcObjects with VBA

19 Lesson overview Tool 工具的事件 使用IDisplayTransformation转换屏幕坐标到地图坐标
使用IGraphicsContainer来管理图形元素 怎么刷新显示 Overview This lesson will discuss the use of UIToolControls in ArcMap. Tool controls differ from buttons in that they allow for user interaction with the display and therefore have many more events that can be coded, such as MouseUp, MouseDown, MouseMove, and so on. Mouse clicks from a tool are returned in display coordinates (pixels). Because ArcMap tools are generally designed to get user input on a map display, you will learn how to convert geometry returned from the mouse into map units. Some common examples of the use of tools in ArcMap will be illustrated in this lesson including panning and zooming, drawing, and providing a user with display feedback. Introduction to Programming ArcObjects with VBA

20 Tool 工具事件 Tools 工具拥有一些事件过程 用于用户交互的事件 用于定义工具行为的事件
Mouse events: MouseUp, MouseMove, MouseDown, DblClick Keyboard events: KeyUp, KeyDown 用于定义工具行为的事件 Enabled CursorID ToolTip Message Tool events Because tools are designed to deal with a variety of sources of user input, they have many more event procedures that can be coded. As a programmer, you have a lot of control over obtaining user input. From the mouse, you can provide code for when the mouse moves, when the mouse button is pressed, when it is released, and when it is double-clicked. You can see if the right or left mouse button is clicked, whether or not the Shift key is held when it is clicked, as well as the location of the mouse cursor. From the keyboard, you can provide code that executes when a key is pressed and when it is released. You can also write logic based on which key is pressed. In addition to the events related to mouse and keyboard input, tools also provide some of the same button events that control appearance, such as Enabled, ToolTip, and Message. The CursorID event can be used to provide a different mouse cursor when your tool is active. Use one of the built-in CursorIDs shown above, or use your own cursor using one of the methods illustrated below. Tools are in design mode while the Visual Basic Editor window is open. Make sure the window is closed (not minimized) to ensure that all tool events are fired properly. 'Use an image on a UserForm in the project … Private Function UIToolControl1_CursorID() As Variant Set UIToolControl1_CursorID = UserForm1.Image1.Picture End Function 'Load a file from disk (*.ico or *.cur) Set UIToolControl1_CursorID = LoadPicture("c:\cursors\magnify.cur") Built-In Cursors Introduction to Programming ArcObjects with VBA

21 怎么在事件中使用X和Y 相关的鼠标事件 返回的是屏幕单位(pixels) MouseUp, MouseDown, MouseMove
Private Sub UIToolControl1_MouseDown(ByVal button As Long, _ ByVal shift As Long, ByVal x As Long, ByVal y As Long) MsgBox "X = " & x MsgBox "Y = " & y End Sub Returning the current mouse position When a user interacts with your tool, the location of their mouse cursor is passed into several of the tool’s event procedures, such as MouseDown, MouseUp, and MouseMove. These coordinates are called x and y in the parameter list (see the example above), and indicate the location of the cursor in display units, called pixels (short for picture elements). Display coordinates are radically different from the map coordinates used to measure geographic data. The size of a pixel will vary with the resolution of your monitor, and the value of y increases as you move down from the origin (0,0), which is in the upper-left of the display. Introduction to Programming ArcObjects with VBA

22 Display transformation
在地图单位和屏幕单位之间转换所用到的方法 ToMapPoint: 转换一个屏幕坐标点 (pixels)到一个地图坐标点 FromMapPoint: 转换一个地图坐标点到屏幕坐标点 使用鼠标输入 捕获鼠标点击的象素值 使用地图点 Display transformation Because you will most often need the location of mouse interaction in map units as opposed to display units, there are methods on the ArcMap display for creating geometry in map coordinates from pixel locations. Use the DisplayTransformation property on the IDisplay interface to access these methods. When converting coordinates from the display, the output map point will be in the current spatial reference defined for your map. Introduction to Programming ArcObjects with VBA

23 转换屏幕坐标系到地图单位 使用 IDisplayTransformation的ToMapPoint方法 返回一个地图单位的点
Dim pMxApp As IMxApplication Set pMxApp = Application Dim pPnt As IPoint Set pPnt = pMxApp.Display.DisplayTransformation.ToMapPoint(x, y) MsgBox "Longitude = " & pPnt.x MsgBox "Latitude = " & pPnt.y DisplayTransformation The DisplayTransformation object, which can be accessed from the AppDisplay object, allows the conversion between display and map coordinates. The example above is typical for tool mouse event procedures that require map coordinates. After using QueryInterface to access the IMxApplication interface on the ArcMap Application object, code is chained together to first access the AppDisplay (IMxApplication :: Display), then the DisplayTransformation (IDisplay :: DisplayTransformation). The ToMapPoint method is called on the IDisplayTransformation interface, and the required x and y pixel coordinate arguments are passed in. A Point object is returned as a result of calling the method (IPoint). Introduction to Programming ArcObjects with VBA

24 Example: Rubberbanding
在模块层定义变量 在 tool’s Select 事件中初始化 在 tool’s MouseDown 事件中输入以下代码 把返回值保存在一个对象中 Private m_pRubberBand As IRubberBand Set m_pRubberBand = New RubberLine 'or RubberPolygon or RubberEnvelope Dim pLine As IPolyline Dim pSymbol As ISymbol Set pSymbol = New SimpleLineSymbol Dim pMxApp As IMxApplication Working with tools Tool controls can implement several event procedures. To share variables between these procedures, use module-level variables. Most often, module-level variables are initialized when the tool is initially selected, the Select event procedure. While the Visual Basic Editor is open, tool controls are in design time mode. To properly capture your events and resolve run time errors, completely close the Visual Basic Editor window and reselect your tool (fire the Select event to re-initialize module-level variables). IRubberBand properties and methods The IRubberBand interface is implemented by several sub-classes of the abstract RubberBand class, such as: RubberEnvelope, RubberLine, RubberPoint, and RubberPolygon. This common interface has the following methods for working with a RubberBand object: TrackExisting: Call to move or reshape an existing shape TrackNew: Call to rubberband a new shape When tracking a RubberBand object, the geometry corresponding to the particular RubberBand coclass is returned (a Line from a RubberLine, a Polygon from a RubberPolygon, etc.). Set pMxApp = Application Dim pDisplay As IScreenDisplay Set pDisplay = pMxApp.Display Set pLine = m_pRubberBand.TrackNew(pDisplay, pSymbol) Introduction to Programming ArcObjects with VBA

25 IGraphicsContainer对象
有 Map 和 PageLayout支持 也可以使用 IActiveView 的 GraphicsContainer属性来获得 用来管理图形元素 AddElement, AddElements, DeleteElement, DeleteAllElements 用来修改图形元素的显示顺序 BringToFront, BringForward SendToBack, SendBackward PutElementOrder IGraphicsContainer interface The IGraphicsContainer interface has methods for working with elements in ArcMap. This is where you will find familiar graphic management methods such as SendToBack, BringToFront, AddElement, DeleteElement, and so on. Remember that elements can be simple graphic elements such as text, shapes, or pictures, and can also be frame elements that contain legends, scalebars, or entire maps. IGraphicsContainer is supported by both the PageLayout and the Map class, which means you can work with map or layout elements by simply QI-ing to IGraphicsContainer on either object. The code below shows an example of adding an element to the map. DIM pGContainer As IGraphicsContainer Set pGContainer = pMxDoc.FocusMap pGContainer.AddElement pCompanyLogo The GraphicsContainer can also be accessed as a property on the IActiveView interface, which is also supported by both the Map and the PageLayout class. Use this property to work with elements in whichever view your user has active. The code below shows an example of adding an element to the Map or the PageLayout, depending on which is currently being viewed. pMxDoc.ActiveView.GraphicsContainer.AddElement pNewText Introduction to Programming ArcObjects with VBA

26 管理图形元素 'Remove all elements from the Map –or- Layout
Set pMxDoc = ThisDocument pMxDoc.ActiveView.GraphicsContainer.DeleteAllElements pMxDoc.ActiveView.Refresh 'Add an element to the Layout Set pMxDoc = ThisDocument Dim pGC As IGraphicsContainer Set pGC = pMxDoc.PageLayout pGC.AddElement pElemArea, 0 pMxDoc.ActiveView.Refresh Adding graphics to a map The IGraphicsContainer interface adds elements (i.e., graphics) to a PageLayout. The Map class also supports the IGraphicsContainer interface. Many of the same graphic elements that you add to a layout (text, markers, polygons, etc.) can also be added directly to a Map. Adding an element to a Map is the same as adding one to a layout, except the geometry defining the element’s position should be in map units rather than page units (e.g., inches). 'Send selected graphics to the back on Layout Dim pGCSelect As IGraphicsContainerSelect Set pGCSelect = pGC ‘QI pGC.SendToBack pGCSelect.SelectedElements pMxDoc.ActiveView.Refresh Introduction to Programming ArcObjects with VBA

27 如何刷新显示 使用IActiveView的Refresh方法 使用IScreenDisplay的Invalidate的方法
刷新所有的显示 (但是不刷新TOC表) 使用IScreenDisplay的Invalidate的方法 只刷新指定的范围 (envelope) 使用IMxDocument的UpdateContents方法 通报该文档对象包含的内容发生了变化 刷行了内容表对象(TOC) Refreshing methods After modifying the ArcMap display, it may be necessary to refresh (redraw) the contents of the display or the document. In ArcObjects, you will find a variety of ways to refresh; choose the method that is most appropriate for the situation. IActiveView :: Refresh—call to redraw the entire display area while in data (Map) or layout (PageLayout) view IScreenDisplay :: Invalidate—call to redraw all layers and elements within a specified area (defined by passing in an Envelope object) IMxDocument :: UpdateContents—call to redraw the legends in the ArcMap Table of Contents Introduction to Programming ArcObjects with VBA

28 部分刷新显示 也许你只需要刷新部分的显示区域 使用IActiveView的PartialRefresh方法 被新图形元素覆盖的区域
比直接刷新整个文档的效率高 使用IActiveView的PartialRefresh方法 用于 Layout 视图或者 Data view 指定什么需要刷新 (e.g., graphics) 指定哪里需要刷新 (an envelope) PartialRefresh PartialRefresh is a method on the IActiveView interface and can therefore be called on a Map or a PageLayout object. PartialRefresh is very similar to IScreenDisplay::Invalidate in that it can be used to redraw only a specified area (envelope) of the display. PartialRefresh gives you more control, however, as it allows you to also specify what you want refreshed (geography, graphics, selection, etc.). Using PartialRefresh is more efficient than redrawing everything on the entire display, especially for maps that contain a lot of data and graphics. Introduction to Programming ArcObjects with VBA

29 Data management(III) Introduction to Programming ArcObjects with VBA

30 Lesson overview 转换数据类型 使用游标来编辑数据 在现有的Dataset中添加字段 Update Insert
There are a variety of ways to manipulate existing data using ArcObjects. In this lesson, you will learn … How to use Name objects WorkspaceNames DatasetNames How to convert feature classes and tables FeatureDataConverter ObjectLoader How to edit using a cursor Update Insert How to add fields and domains Introduction to Programming ArcObjects with VBA

31 数据处理对象 FeatureDataConverter, ExportOperation对象 ObjectLoader对象
提供以下格式的转换功能 coverage, shapefile, and geodatabase ObjectLoader对象 追加数据到现有的 feature class 或 table Related objects对象 FieldChecker: 使用字段名来定位问题 EnumInvalidObject: 枚举在转换或者追加过程中无效的要素(feature) Convert, export, load FeatureDataConverter is a coclass that can convert feature classes, feature datasets, or tables to new output datasets. Use a FeatureDataConverter object to convert individual feature classes and tables, or even entire feature datasets (e.g., ArcInfo coverages). The FeatureDataConverter object lets you convert data between geodatabases, shapefiles, and coverages. Most types of feature data are currently supported (except for annotation). FeatureDataConverter is suitable for loading large amounts of data. When importing to a geodatabase, you can specify an interval for committing data; you can also specify an ArcSDE configuration keyword to control specific storage parameters for an ArcSDE geodatabase. ExportOperation is a coclass that can be used to export a feature class or a table. The ExportOperation coclass offers similar functionality to the feature data converter but in a simplified form. It corresponds to the export data function available in ArcMap by right-clicking on a layer in the Table of Contents. ObjectLoader is used to append records from one table (or feature class) to another. The IObjectLoader interface contains a single method, LoadObjects. Validating fields and records A FieldChecker object can be used to validate a fields collection. This can be especially useful when converting data between formats, as some datasets might contain field names that are illegal in other formats. A FieldChecker will produce a new fields collection with standard fixes for invalid fields it encounters (by adding an underscore to the field name, for example, UID_). The FieldChecker will provide standard names for geometry and OID fields when converting to geodatabase format (Shape and OBJECTID). When loading or converting features using the ObjectLoader or FeatureDataConverter, an enum of invalid objects is returned (IEnumInvalidObject). Using this enum, a programmer can easily see which objects (rows or features) could not be loaded or converted. Introduction to Programming ArcObjects with VBA

32 转换要素类feature classes 使用IFeatureDataConverter的ConvertFeatureClass方法
转换输入的要素类到一个新的输出要素类 所需要的参数 Input and output FeatureClassNames Output FeatureDatasetName A QueryFilter Many Others … 'Create a new FeatureDataConverter object Dim pFDConvert As IFeatureDataConverter Set pFDConvert = New FeatureDataConverter Using the FeatureDataConverter The FeatureDataConverter object allows a programmer to export feature classes, tables, or feature datasets to a new output (of the same or different format). FeatureDataConverter is a coclass, so it can be created with the new keyword. Using the IFeatureDataConverter interface, you can call one of three methods to convert data: ConvertFeatureClass, ConvertFeatureDataset, or ConvertTable. Use the IFeatureProgress interface to track the progress of a conversion. Below is a description of the required arguments for IFeatureDataConverter :: ConvertFeatureClass. InputDatasetName: IFeatureClassName—a Name object that specifies the feature class to be converted. InputQueryFilter: IQueryFilter—a QueryFilter object used to define a subset of features to be converted. outputFDatasetName: IFeatureDatasetName—a Name object that defines the (new or existing) feature dataset into which the converted feature class will be written. outputFClassName: IFeatureClassName—a Name object that defines the new output feature class. OutputGeometryDef: IGeometryDef—a GeometryDef object that defines the spatial reference for the output feature class. If Nothing is used for this argument, the spatial reference of the output feature dataset or the input feature class will be used. OutputFields: IFields—a fields collection for the output feature class. If simply exporting a feature class to the same format, the fields collection from the input feature class can be used. If exporting between formats, it is a good idea to use a FieldChecker object to make sure the fields are valid for the output format. configKey: String—a string that specifies an ArcSDE configuration keyword. FlushInterval: Long—an integer that specifies the interval for committing features to the new feature class (when exporting to geodatabase). parentHWnd: Long—an integer specifying the application’s window handle (you will usually use Application.hWnd to satisfy this argument). IFeatureDataConverter :: ConvertFeatureClass returns IEnumInvalidObject, which is an enum of all features that could not be converted. Introduction to Programming ArcObjects with VBA

33 Exercise 14A overview Convert an ArcInfo coverage to a Personal Geodatabase IFeatureDataConversion :: ConvertFeatureClass 在第五天代码阅读时提供 Introduction to Programming ArcObjects with VBA

34 使用游标来编辑数据 Update 和 Insert 类型的游标
比使用 ITable::CreateRow, ITable::Store等方法更快 在大数据库的情况下更有效 Use to add, delete, or modify rows or features ICursor::InsertRow (IFeatureCursor::InsertFeature) ICursor::DeleteRow (IFeatureCursor::DeleteFeature) ICursor::UpdateRow (IFeatureCursor::UpdateFeature) Using a cursor to edit records You have already learned to create records (rows or features) using methods such as CreateRow and CreateFeature. You have learned to change field values by setting properties such as Value and Shape, and to commit your edits by calling the Store method. Although the above steps work fine for editing a table or feature class, you may find it much more efficient to use a cursor or feature cursor, particularly when editing a large number of records; you can expect a cursor to perform the edits as much as 2,000 times faster. Introduction to Programming ArcObjects with VBA

35 编辑游标 游标返回的类型决定于所使用的方法 Update cursor Insert cursor Update method
Use to update or delete records in the database Insert cursor Insert method Use to insert new records into the database Dim pCursor As IFeatureCursor Set pCursor = pFClass.Update(pQFilter, False) Dim pCursor As IFeatureCursor Set pCursor = pFClass.Insert(True) Types of cursors There are three types of cursor objects that can be obtained from a Table or FeatureClass. The type of cursor returned depends solely on the method that was used to create it. As a programmer using one of these cursors, you need to be mindful of the type of cursor you create and make sure that it is suited to your purpose. Each cursor type will have the same available interfaces (e.g., ICursor, IFeatureCursor) with the same methods and properties available. Calling some of these methods with the wrong type of cursor, however, will return an error. Update cursor Update cursors are created by calling the Update method on a Table or FeatureClass. An Update cursor is used to update or delete records in the database from which the cursor was created (Table or FeatureClass). Like Search cursors, Update cursors are created with a QueryFilter object, giving you the ability to store a subset of records in the returned cursor (or all records by using the Nothing keyword). If you create a cursor as an Update cursor, you should not try to call the InsertRow (InsertFeature) method. This method only works on an Insert cursor. Insert cursor Insert cursors are created by (you guessed it) using the Insert method on a Table or a FeatureClass. Use an Insert cursor to insert new records into the database from which the cursor was created (Rows in a Table or Features in a FeatureClass). Unlike Search and Update cursors, the Insert method does not take a QueryFilter as a parameter. Insert cursors do not support the NextRow (NextFeature) method, nor the UpdateRow method. Introduction to Programming ArcObjects with VBA

36 例子: 使用Updata游标更新编辑错误的属性
Dim pQFilt As IQueryFilter Set pQFilt = New QueryFilter pQFilt.WhereClause = "StateName = ‘newmexico’" Dim pUpCursor As IFeatureCursor Set pUpCursor = pFClass.Update(pQFilt, False)'Only "newmexico" Dim pFeature As IFeature Set pFeature = pUpCursor.NextFeature Do Until pFeature Is Nothing pFeature.Value(3) = “New Mexico” ‘改正错误 pUpCursor.UpdateFeature pFeature ‘提交记录 Set pFeature = pUpCursor.NextFeature 'Move to the next Loop MsgBox "Features have been updated" Example: Updating records with a cursor When producing an update cursor, you can specify a query filter to restrict the records returned. In the example, the query filter is used to make a subset of misspelled records. Remember: to access all records inside a cursor, you need to use a Do While or a Do Until loop. Before entering the loop, the first feature is pulled out of the FeatureCursor (pFCursor.NextFeature) and stored in a variable (pFeature). The loop will then check to see if pFeature is Nothing, and until it is, the loop will continue to execute. If, at this point, your FeatureCursor had no records (i.e., nothing met the search criteria) the first object retrieved from the cursor would be Nothing, and therefore the body of the loop would never be executed. Inside the loop, a new value is written to the feature’s fourth field (presumably, the StateName field). The dataset is then updated by calling the UpdateFeature method on the cursor. The next feature is again pulled from the cursor by calling the NextFeature method. Once the loop is complete, a message box is displayed telling the user that features were successfully updated. Introduction to Programming ArcObjects with VBA

37 添加一个字段 使用Itable的AddField 方法为现有的dataset对象添加一个字段 使用一个Update游标来计算并为字段的赋值
不需要把Field加入到Fields对象中 使用一个Update游标来计算并为字段的赋值 Dim pAverageFld As IFieldEdit Set pAverageFld = New Field With pAverageFld .Name = "Average" .Type = esriFieldTypeInteger .AliasName = "Average Income" .Length = 16 End With pTable.AddField pAverageFld Adding a new field to an existing table or feature class When producing fields for a new table or feature class, a programmer can simply make a new field, set its properties, then add it to the Fields collection. The process for creating a new field in an existing dataset is similar, except there is no need to deal with the Fields collection. After making a new field (using the New keyword) and setting its properties, simply call the AddField method on ITable or IFeatureClass, pasting in the new Field object as the required argument. After adding a field to an existing dataset, the most efficient way to calculate its values is by using an update cursor. Introduction to Programming ArcObjects with VBA

38 Working with layout elements(IIII)
Introduction to Programming ArcObjects with VBA

39 Lesson overview 增加框架元素到PageLayout 使用 graphics container 符号化回顾 打印和输出布局
Symbols Colors Elements 打印和输出布局 Working with Layout Elements This lesson will discuss many of the objects related to adding graphics to an ArcMap page layout or map. Graphics, whether they are things such as scalebars, north arrows, markers, lines, or text, are generically referred to as elements. Each of these elements may be added to a page layout, or possibly a map. When working with elements, you may also find it necessary to use related objects such as symbols, colors, and geometry (to define the elements position on the page or map), all of which will be covered in this lesson. Lesson overview Object model overview Working with layout frame elements Finding existing elements, creating new ones Review: Symbols, Colors, Elements Referencing elements in the ArcMap style gallery Outputting a layout to a printer or file Introduction to Programming ArcObjects with VBA

40 对象模型图 ArcMap OMD Object model overview
From the simple object model diagram above, you can tell that a PageLayout is composed of (potentially) several Element objects. Element is an abstract class that has several sub-types. On the IElement interface (implemented by every subclass of Element) there is a Geometry property. An element added to a layout or map uses this property to specify its location. An element’s geometry can be defined in map units or page units, whichever is appropriate. Graphic and Frame elements The two direct sub-types of Element are themselves abstract classes and represent the two fundamental types of elements: GraphicElements—text, shape, and picture elements FrameElements—MapFrames (i.e., data frames), TableFrames, OLEFrames, and MapSurroundFrames (e.g., north arrows, legends, and scalebars) Apart from a handful of abstract classes, all elements are creatable (coclasses). As a programmer, you can create new text, graphic, or map elements to add to your layout. Most graphic elements will have a Symbol property that allows you to control the color and style of the graphics you create. Frame elements are used as containers in the layout. MapFrames contain a collection of layers (in other words, a data frame), while a MapSurroundFrame element is used to contain objects that are related to a particular Map, such as a scalebar, north arrow, or legend. It is important to make a distinction between a MapSurroundFrame, and the object it contains, a MapSurround. MapSurrounds, such as a Legend, are related directly to a Map (data frame), and must be contained within a MapSurroundFrame in order to be represented on the layout. Other types of FrameElements include TableFrame, for containing a Table object, and an OLEFrame, for containing another application (such as a Microsoft Word document). Introduction to Programming ArcObjects with VBA

41 回顾: Elements 有一些可以创建的对象 图形元素包含 框架元素 Line, polygon, marker
Text and pictures 框架元素 在 PageLayout上 Map frames North arrows, legends, scale bars Table frames Example: Count the types of elements on the layout Public Sub CountElements () Dim pMxDoc As IMxDocument Dim pGC As IGraphicsContainer Set pMxDoc = ThisDocument Set pGC = pMxDoc.PageLayout pGC.Reset Dim intMapFrames As Integer, intMSFrames As Integer Dim intTextElements As Integer, intOtherElements As Integer Dim pElement As IElement Set pElement = pGC.Next Do Until pElement Is Nothing If TypeOf pElement Is IMapFrame Then intMapFrames = intMapFrames + 1 ElseIf TypeOf pElement Is IMapSurroundFrame Then intMSFrames = intMSFrames + 1 ElseIf TypeOf pElement Is ITextElement Then intTextElements = intTextElements + 1 Else intOtherElements = intOtherElements + 1 End If Loop MsgBox "The layout has " & intMapFrames & " map frames, " & _ intMSFrames & " map surround frames, " & _ intTextElements & " text elements, and " & _ intOtherElements & " miscellaneous element types." End Sub Introduction to Programming ArcObjects with VBA

42 框架元素FrameElements 属于 PageLayout 的附属 MapSurroundFrame elements
MapSurrounds对象的容器 (e.g., Scalebars) 内容时动态更新的 MapSurroundFrame MapSurround MapSurrounds and MapSurroundFrames The terms MapSurround and MapSurroundFrame can be a little confusing. To distinguish these objects, remember that a MapSurroundFrame is a type of Element, and can be added to a PageLayout. A MapSurround object, on the other hand, is always contained within a MapSurroundFrame and has a dynamic relationship with a Map (data frame). Introduction to Programming ArcObjects with VBA

43 例子: 在布局上引用MapFrames对象
Dim pMxDoc As IMxDocument Set pMxDoc = ThisDocument Dim pGC As IGraphicsContainer’枚举对象 Set pGC = pMxDoc.PageLayout pGC.Reset ‘移动到最前面 Dim pElem As IElement Set pElem = pGC.Next ‘取得第一个条目 Do Until pElem Is Nothing If (TypeOf pElem Is IMapFrame) Then ‘有多种类型 Dim pMapEnvelope As IEnvelope Dim intW As Integer, intH As Integer Set pMapEnvelope = pElem.Geometry.Envelope intW = pMapEnvelope.Width intH = pMapEnvelope.Height MsgBox "Map Frame = " & intW & " by " & intH End If Set pElem = pGC.Next ‘取得下一个条目 Loop Retrieving an element from the GraphicsContainer Elements in a GraphicsContainer are organized like objects contained by an enum. Elements cannot be referenced directly by their index position inside the GraphicsContainer, but must be located within a looping routine. If searching for a particular type of element (text, picture, etc.), use the TypeOf statement to identify the element(s) you want to work with. The example above uses a Do While loop to iterate through each element in the GraphicsContainer. Inside the loop, a test is made to determine if the current element is a map frame (supports the IMapFrame interface). If it is, the element’s dimensions are stored, and then reported in a message box inside the loop. An ArcMap document always has at least one map frame, but could potentially have many more. The code above will report the dimensions of all map frames in the layout. Finding an element by name Elements added to the GraphicsContainer can be given a name by using the Name property on IElementProperties. By assigning a name to an element, it can be easily referenced later by using code such as that shown below: Dim pElementProps As IElementProperties Set pElementProps = pGContainer.Next Do Until pElementProps Is Nothing '*Loop thru all elements If pElementProps.Name = "DougherNorth" Then '*Look for this one … Dim pLegendFrame As IMapSurroundFrame Set pLegendFrame = pElementProps '*QueryInterface (QI) Exit Do '*Exit the loop once it's found End If Loop Introduction to Programming ArcObjects with VBA

44 打印一个a layout 多样的输出子类 Paper class 发送到打印机或者是文件
EmfPrinter (增强的 meta-file) PsPrinter (支持打印机脚本) ArcPressPrinter Paper class 用来管理打印纸张设置 发送到打印机或者是文件 Example: Printing the layout to a postscript file Private Sub PrintToPSFile(aLayout As IPageLayout, FileName As String) Dim pMxApp As IMxApplication, pPrinter As IPrinter Set pMxApp = Application Set pPrinter = New PsPrinter Set pPrinter.Paper = pMxApp.Paper pPrinter.PrintToFile = FileName Dim pPrintEnv As IEnvelope Set pPrintEnv = New Envelope aLayout.Page.GetDeviceBounds pPrinter, 0, 0, pPrinter.Resolution, pPrintEnv Dim rectOut As tagRECT rectOut.Left = pPrintEnv.xMin rectOut.Top = pPrintEnv.yMin rectOut.Right = pPrintEnv.xMax rectOut.bottom = pPrintEnv.yMax Dim pPageBounds As IEnvelope Set pPageBounds = New Envelope aLayout.Page.GetPageBounds pPrinter, 0, 0, pPageBounds Dim hDc As OLE_HANDLE hDc = pPrinter.StartPrinting(pPrintEnv, 0) Dim pActiveView As IActiveView Set pActiveView = aLayout pActiveView.Output hDc, pPrinter.Resolution, rectOut, pPageBounds, Nothing pPrinter.FinishPrinting MsgBox "Layout sent to " & FileName, vbInformation, "Printing complete!" End Sub Introduction to Programming ArcObjects with VBA

45 输出 layout对象 多样化的输出格式 使用的IActiveView方法StartExporting
Adobe Acrobat (*.pdf) JPEG ArcPress 使用的IActiveView方法StartExporting 输出聚焦的Map或PageLayout Example: Exporting the layout as a jpeg Private Sub Export(aLayout As IActiveView, aPath As String, DPI As Integer) Dim rectOut As tagRECT rectOut = aLayout.exportFrame Dim pExporter As IExporter Set pExporter = New JpegExporter Dim pEnv As IEnvelope Set pEnv = New Envelope pEnv.PutCoords rectOut.Left, rectOut.Top, rectOut.Right, rectOut.bottom pExporter.ExportFileName = aPath pExporter.PixelBounds = pEnv pExporter.Resolution = DPI 'Recalc the export frame to handle the increased number of pixels Set pEnv = pExporter.PixelBounds Dim xMin As Double, yMin As Double, xMax As Double, yMax As Double pEnv.QueryCoords xMin, yMin, xMax, yMax rectOut.Left = xMin rectOut.Top = yMin rectOut.Right = xMax rectOut.bottom = yMax Dim hDc As Long hDc = pExporter.StartExporting aLayout.Output hDc, DPI, rectOut, Nothing, Nothing pExporter.FinishExporting MsgBox "Export complete!", vbInformation End Sub Introduction to Programming ArcObjects with VBA

46 例子: 把Layout输出到一个Jpg文件
Private Sub Export(aLayout As IActiveView, aPath As String, DPI As Integer) Dim rectOut As tagRECT rectOut = aLayout.exportFrame Dim pExporter As IExporter Set pExporter = New JpegExporter Dim pEnv As IEnvelope Set pEnv = New Envelope pEnv.PutCoords rectOut.Left, rectOut.Top, rectOut.Right, rectOut.bottom pExporter.ExportFileName = aPath pExporter.PixelBounds = pEnv pExporter.Resolution = DPI

47 例子: 把Layout输出到一个Jpg文件
'Recalc the export frame to handle the increased number of pixels Set pEnv = pExporter.PixelBounds Dim xMin As Double, yMin As Double, xMax As Double, yMax As Double pEnv.QueryCoords xMin, yMin, xMax, yMax rectOut.Left = xMin rectOut.Top = yMin rectOut.Right = xMax rectOut.bottom = yMax Dim hDc As Long hDc = pExporter.StartExporting aLayout.Output hDc, DPI, rectOut, Nothing, Nothing pExporter.FinishExporting MsgBox "Export complete!", vbInformation End Sub

48 考试题目 1、建立一个UIButtonControl,单击该按钮,加载磁盘上C:\USA\States.shp的 ShapeFile文件到ArcMap的地图中。 2、建立一个UIToolControl,使用该工具时,可以点选其中一个多边形对象,并把选择中记录的序号为6的字段值显示出来。 3、最后的结果是: 代码: ××××××××××××××××××××××××××××××××××××××× Private Sub UIButtonControl1_Click() Dim pWF As IWorkspaceFactory Set pWF = New ShapefileWorkspaceFactory Dim pFWS As IFeatureWorkspace Set pFWS = pWF.OpenFromFile("C:\USA", 0) Dim pFClass As IFeatureClass Set pFClass = pFWS.OpenFeatureClass("STATES") Dim pFLayer As IFeatureLayer Set pFLayer = New FeatureLayer Set pFLayer.FeatureClass = pFClass Dim pDataset As IDataset Set pDataset = pFClass pFLayer.Name = pDataset.Name Dim pDoc As IMxDocument Set pDoc = ThisDocument pDoc.AddLayer pFLayer End Sub ×××××××××××××××××××××××××××××××××××××××× ×××××××××× Private Sub UIToolControl2_MouseDown(ByVal button As Long, ByVal shift As Long, ByVal x As Long, ByVal y As Long) Dim pScreenDisp As IScreenDisplay Dim pDt As IDisplayTransformation Dim pPt As IPoint Dim pMap As IMap Dim pLayer As IFeatureLayer Dim pFeature As IFeature Dim pFeatureCursor As IFeatureCursor Dim pSpatialFilter As ISpatialFilte '把屏幕坐标点转换成地图坐标点 Set pScreenDisp = pDoc.ActiveView.ScreenDisplay Set pDt = pScreenDisp.DisplayTransformation 'get the MouseDown location in map units Set pPt = pDt.ToMapPoint(x, y) '引用一个图层 'the tutorial expects the first layer to 'serve as the target Set pMap = pDoc.ActiveView.FocusMap Set pLayer = pMap.Layer(0) pLayer.Selectable = True '定义空间过滤条件 'create a SpatialFilter to be used in 'a point in polygon selection Set pSpatialFilter = New SpatialFilter With pSpatialFilter Set .Geometry = pPt .GeometryField = pLayer.FeatureClass.ShapeFieldName .SpatialRel = esriSpatialRelWithin End With '空间查询 Set pFeatureCursor = pLayer.Search(pSpatialFilter, False) 'pFeature is a polygon feature Set pFeature = pFeatureCursor.NextFeature MsgBox pFeature.Value(6) ×××××××××××××××××××××××××××××××××××××××× Introduction to Programming ArcObjects with VBA


Download ppt "Symbolizing elements and layers(I)"

Similar presentations


Ads by Google