Library dependencies: System, Geometry, Display, Output, GeoDatabase, Carto
The Display library contains objects used for the display GIS data. In addition to the main display objects that are responsible for the actual output of the image, the library contains objects that represent symbols and colors, controlling the properties of entities drawn on the display. The library also contains objects that provide the user with visual feedback when interacting with the display.
The objects that implement this functionality are grouped into a number of library subsystems. These library subsystems are:

The Display object abstracts a drawing surface. A drawing surface is any hardware device, export file, or memory stream that can be represented by a Windows Device Context. Each display manages its own Transform object which handles the conversion of coordinates from real-world space to device space and back. The following standard displays are provided: ScreenDisplay abstracts a normal application window. It implements scrolling and backing store (multiple backing layers are possible). SimpleDisplay abstracts all other devices that can be rendered to using a Windows Device Context, such as printers, metafiles, bitmaps, and secondary windows.
The display objects allow application developers to easily draw graphics on a variety of output devices. These objects allow you to render shapes stored in real-world coordinates to the screen, the printer, and export files. Application features such as scrolling, backing store, print "tiling", and printing to a frame can be easily implemented. If some desired behavior is not supported by the standard objects, custom objects can be created by implementing one or more of the standard display interfaces.
In general, you must have a device context to do any drawing in windows. The HDC (handle to a device context) defines the device that you are drawing on. Some example devices are windows, printers, bitmaps, and metafiles. In ArcObjects, a display is simply a wrapper for a windows device context.
Use a SimpleDisplay coclass when you want to draw on a printer, export file, or simple preview window. Specify the HDC that you want to use to StartDrawing. This tells the display which window, printer, bitmap, or metafile to draw on. The HDC is created outside of ArcObjects using a Windows GDI function call.
Use a ScreenDisplay coclass when you want to draw maps to the main window of your application. This coclass handles advanced application features such as display caching and scroll bars. Specify the HDC for the associated window to StartDrawing. Normally, this is the HDC returned when you call the Windows GDI BeginPaint function in your application's WM_PAINT handler. Alternatively, you may specify 0 as the HDC parameter for StartDrawing, and an HDC for the associated window is automatically created. Normally, a ScreenDisplay uses internal display caches to boost drawing performance. During a drawing sequence, output is directed to the active cache and once per second, the window (i.e., the HDC specified to StartDrawing) is progressively updated from the active cache. If you want to prevent progressive updates (i.e., if you would rather update the window once when drawing has completed), specify the recording cache HDC (IScreenDisplay.getCacheMemDC(esriScreenRecording)) to StartDrawing.
Use the IDisplay interface to draw points, lines, polygons, rectangles, and text on a device. Access to the display object's DisplayTransformation object is provided by this interface.
DisplayTransformation – This object defines how real-world coordinates are mapped to a output device. Three rectangles define the transformation. The Bounds specifies the full extent in real-world coordinates. The VisibleBounds specifies what extent is currently visible. And the DeviceFrame specifies where the VisibleBounds appears on the output device. Since the aspect ratio of the DeviceFrame may not always match the aspect ratio of the specified VisibleBounds, the transformation calculates the actual visible bounds that fits the DeviceFrame. This is called the FittedBounds and is in real-world coordinates. All coordinates can be rotated about the center of the visible bounds by simply setting the transformation’s Rotation property.
Here's the basic idea behind display caching. The main application window is controlled by a view (IActiveView). There are currently two view coclasses implemented: Map (data view) and PageLayout (layout view). ScreenDisplay makes it possible for clients to create any number of caches (a cache is just a device dependent bitmap). When a cache is created, the client gets a cacheID. The id is used to specify the active cache (last argument of StartDrawing, i.e., where output is directed), invalidate the cache, or draw the cache to a destination HDC. In addition to dynamic caches, the ScreenDisplay also provides a recording cache that accumulates all drawing that happens on the display. Clients manage recording using the StartRecording and FinishRecording methods.
To see how caches are implemented within ArcObjects the Map coclass will be examined. In the simplest case, Map creates one cache for all the layers, another cache if there are annotation or graphics, and a third cache if there's a feature selection. It also records all output. (In addition to these caches, it's also possible for individual layers to request a private cache by returning true for their Cached property. If a layer requests a cache, the Map creates a separate cache for the layer and groups the layers above and below it into different caches.) The IActiveView.partialRefresh method uses it's knowledge of the cache layout to invalidate as little as possible so that we can draw as much as possible from cache. Given these caches, all of the following scenarios are possible:
The ScreenDisplay can record what gets drawn. Use startRecording() and stopRecording() to let the display know what exactly should be recorded. Use drawCache(esriScreenRecording) to display what was recorded. Use getCacheMemDC(esriScreenRecording) to get a handle to the memory device context for the recording bitmap. This functionality has several important uses.
IScreenDisplay screenDisplay;
MapControl mapControl;
boolean isCacheDirty = screenDisplay.isCacheDirty((short)esriScreenCache.esriScreenRecording);
if(isCacheDirty){
screenDisplay.startRecording();
screenDisplay.startDrawing(mapControl.getHWnd(),(short)esriScreenCache.esriNoScreenCache);
drawContents();
screenDisplay.finishDrawing();
screenDisplay.stopRecording();
}else{
screenDisplay.drawCache(mapControl.getHWnd(), (short)esriScreenCache.esriScreenRecording,null,null);
}
If any part of your map contains transparency it will affect how things get refreshed. When a transparent layer draws, everything below it, becomes part of the layer's rendering. As a result, the transparent layer must redraw from scratch every time that something below it changes.
Text also has transparency if the anti-aliasing setting is turned on in Microsoft Windows. This means that the text uses the layers that draw below it to carry out the anti-aliasing (the edges of the text are blended into the background). As a result, the annotation or auto-labels must draw whenever a layer changes.
Set the cached flag on the layers you want to have their own display cache. Then reactivate the view.
public void enableLayerCaches(MapBean map){
try{
for(int i=0;i<map.getLayerCount();i++)
map.getLayer(i).setCached(true);//Pass the values as needed.
//Reactivate the display...
map.getActiveView().deactivate();
map.getActiveView().activate(map.getHWnd());
map.getActiveView().refresh();
}catch(Exception e){
e.printStackTrace();
}
}
Understanding how rotatation is implemented within the display objects is important since it affects all entities that are displayed. Rotation happens below the transformation level so clients of DisplayTransformation always deal with unrotated shapes. For example, when you get a shape back from one of the transform routines, it's in unrotated space. Also, when you specify an extent to the transform, the extent is also in unrotated space. When working with polygons everything just works. When working with envelopes, things are more complicated because rotated rectangles cannont be represented. This is best illustrated with 2 examples:
Getting a rectangle from the transform. For example, let's say you want a rectangle representing the client area of the window. Since the user is seeing rotated space on the display, it's not possible to represent the requested area as an Envelope. The four corners of the rectangle have unique x and y values in map space. The internal representation of the Envelope coclass assumes shared x and y values for the sides. As a result the envelope returned by DisplayTransformation.FittedBounds isn't really what you want because a rectangular polygon is needed to accurately represent the client area in unrotated map space. Currently there's a bug that causes FittedBounds to return the same envelope that is returned when there is no rotation. When this is fixed, it should return a slightly expanded envelope as you expected. Most clients avoid using an envelope when there is rotation and implement code like the following to find the rectangular polygon that matches some rectangle on the user's display:
inline void ToUnrotatedMap(const RECT& r, IGeometry* pBounds, IDisplayTransformation* pTransform)
{
WKSPoint mapPoints[5];
POINT rectCorners[4] = {{r.left, r.bottom}, {r.left, r.top}, {r.right, r.top}, {r.right, r.bottom}};
pTransform->TransformCoords(mapPoints, rectCorners, 4, esriTransformToMap | esriTransformPosition);
// build polygon from mapPoints
mapPoints[4] = mapPoints[0];
IPointCollectionPtr(pBounds)->SetWKSPoints(5, mapPoints);
ITopologicalOperator2Ptr(pBounds)->put_IsKnownSimple(VARIANT_TRUE);
}
Specifying a rectangle to the transform. Remember that the client needs to work in unrotated space and let the transform handle the rotation just before displaying. What does this mean in the simple case of dragging a zoom rectangle. First, the user sees rotation space. The rectangle they drag is in rotation space. (Note: the tool uses code like above to create a rectangular polygon representing the area selected by the user.) The tool needs to convert the rectangle to unrotated space before specifying it to the transform. The following code shows how to do this (pRotatedExtent is a rectangular polygon that exactly matches the rectangle dragged by the user):
IArea area = (IArea)rotatedExtent;
IPoint center = area.getCentroid();
ITransform2D transform = (ITransform2D)rotatedExtent;
transform.rotate(center, 45);
IEnvelope newExtent = rotatedExtent.getEnvelope();
In order to cause a display to redraw, the Invalidate routine must be called. Most clients never use IScreenDisplay.invalidate however. The reason is that if there is a view being used in your application, i.e., the Map or PageLayout coclass, the view should be used for refreshing the screen, i.e., Refresh, PartialRefresh. The view manages the display's caches and knows the best way to carry out invalidation. Just make sure PartialRefresh is called using the most specific arguments possible. Also, only call Refresh when absolutely necessary since this is usually a very time consuming operation.
One Stop Invalidation - In order to allow views (Map and PageLayout) to completely manage display caching, all invalidation must go through the view. Calling IActiveView.refresh always draws everything. This is very inefficient. The method called PartialRefresh should be used whenever possible. It lets you specify what part of the view to redraw and allows the view to work with display caches in a way the allows drawing to be quick and efficient.
| Draw Phase | Map | PageLayout |
|---|---|---|
| esriViewBackground | unused | page/snap grid |
| esriViewGeography | layers | unused |
| esriViewGeoSelection | feature selection | unused |
| esriViewGraphics | labels/graphics | graphics |
| esriViewGraphicSelection | graphic selection | element selection |
| esriViewForeground | unused | snap guides |
Arguments for PartialRefresh
The table below shows some example calls to the partial refresh method; note the use of optional arguments:
| Action | Method Call |
|---|---|
| Refresh Layer | map.partialRefresh(esriViewDrawPhase.esriViewGeography, layer,null); |
| Refresh All Layers | map.partialRefresh(esriViewDrawPhase.esriViewGeography, null, null); |
| Refresh Selection | map.partialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, null); |
| Refresh Labels | map.partialRefresh(esriViewDrawPhase.esriViewGraphics, null, null); |
| Refresh Element | layout.partialRefresh(esriViewDrawPhase.esriViewGraphics, element, null); |
| Refresh All Elements | layout.partialRefresh(esriViewDrawPhase.esriViewGraphics, null, null); |
| Refresh Selection | layout.partialRefresh(esriViewDrawPhase.esriViewGraphicSelection, null, null); |
Example uses of PartialRefresh
Note: invalidating any phase will cause the recording cache to be invalidated. To force a redraw from the recording cache, use the following call
screenDisplay.invalidate(null, false, esriScreenCache.esriNoScreenCache)
This section describes the events that are fired when a map draws. To provide better insight into drawing events, drawing order and display caching are discussed as well.
To better understand the events that are fired when a map draws, the following section describes the order that objects are drawn for each kind of view.
Map (data view) – The following shows top to bottom order, i.e., each item is drawn above the items below it:
| Object | Phase | Cache |
|---|---|---|
| Graphic Selection | esriViewForeground | none |
| Clip Border | esriViewForeground | none |
| Feature Selection | esriViewGeoSelection | selection |
| Auto Labels | esriViewGraphics | annotation |
| Graphics | esriViewGraphics | annotation |
| Layer Annotation | esriViewGraphics | annotation |
| Layers | esriViewGeography | layer(s) |
| Background | esriViewBackground | bottom layer |
Map Class Drawing Order
PageLayout – The following shows top to bottom order, i.e., each item is drawn above the items below it:
| Object | Phase | Cache |
|---|---|---|
| Snap Guides | esriViewForeground | none |
| Selection | esriViewGraphicSelection | selection |
| Elements | esriViewGraphics | element |
| Snap Grid | esriViewBackground | element |
| Print Margins | esriViewBackground | element |
| Paper | esriViewBackground | element |
PageLayout class drawing order
The following IActiveViewEvents events can be used to add custom drawing to your application:
The AfterDraw event is fired after every phase of drawing. To draw a graphic into a cache, use the following design:
Not all of the views fire all of the events. Additionally, if a view is partially refreshed, the phases that draw from cache do not fire their afterDraw event. For example, if the selection is refreshed, all of the layers draw from cache. As a result, the afterDraw(esriViewGeography) event does not fire. However, there is an exception, in the case of esriViewForeground, the event is fired everytime the view draws. Even if everything in the map draws from the recording cache, the foreground event still fires.
The afterItemDraw is fired after each feature or graphic is displayed and can seriously impact drawing performance if a connected handler is not efficient. Normally clients connect to the aAfterDraw event. Note that it's important to check the second argument and respond to the appropriate phase of drawing since the afterDraw routine will be called several times when the map is drawn.
For efficiency, IActiveView has a property called verboseEvents. It can be used to limit the number of events that are fired. If verboseEvents=false, afterItemDraw is not fired. This is the default setting.
The following tables shows the device context that is active when each of the AfterDraw events is fired:
| Event | Active HDC |
|---|---|
| esriViewForeground | window |
| esriViewGraphics | annotation cache |
| esriViewGeoSelection | selection cache |
| esriViewGeography | top layer cache |
| esriViewBackground | bottom layer cache |
Map class afterDraw Device Contexts
| Event | Active HDC |
|---|---|
| esriViewForeground | window |
| esriViewGraphicSelection | selection cache |
| esriViewGraphics | element cache |
| esriViewBackground | element cache |
Create a private cache
For drawing graphics (events), you probably want to use esriViewGraphics.afterDraw has two arguments, screenDisplay and drawPhase. It gets called for each of the phases so make sure you only draw when your phase is specified. Draw directly to the display and don't worry about caches. The startDrawing and finishDrawing methods are called by Map. If the phase you are drawing after is cached, your drawing will automatically be cached.
Dim pActiveView As IActiveView IActiveView activeView = map.getActiveView(); //map is MapBean Dim pScreen As IScreenDisplay IScreenDisplay screenDisplay = activeView.getScreenDisplay(); short cacheID = screenDisplay.addCache();
if(phase != esriViewDrawPhase.esriViewXXX)return;
if(display != null){
//Draw Directly to the output device
drawMyStuff(display);
return;
}
//Draw to Screen using Cache if Possible
int windowHDC = display.getWindowDC();
boolean isDirty = display.isCacheDirty(myCacheID);
if(isDirty){
//Draw from Scratch
display.finishDrawing();
display.startDrawing(myCacheID, isDirty);
drawMyStuff(display); //Map::cacheDraw handles finish drawing
}else{
//Draw From Cache
display.drawCache(windowHDC, myCacheID, null, null);
}
Both symbols and images can make use of transparent colors. The transparency (alpha blend) algorithm is raster based. Vector drawing must first be converted to raster in order to support it. Transparent objects are drawn to a source bitmap. The background that the objects are drawn on must be stored in a background bitmap. Transparency is accomplished by blending the source bitmap into the background bitmap using either a single transparency value for all the bits or a mask bitmap containing transparency values for each individual pixel. To support transparency, IDisplay provides the BackgroundDC attribute that can be used to get a bitmap containing all of the drawing that has happened in the current drawing sequence.
The transparency algorithm is encapsulated into the display filter object: TransparencyDisplayFilter. The same filter coclass can be used by feature layers, raster layers, elements, third parties, etc.
To draw with transparency, do the following:
TransparencyDisplayFilter filter = new TransparencyDisplayFilter();
filter.setTransparency((short)100);
display.startDrawing(hDC, cacheID);
display.setFilterByRef(filter);
drawToDisplay();
display.setFilterByRef(null);
display.finishDrawing();
For raster layers, drawToDisplay() means get the destination DC from the display and BitBlt the raster image to it.
When the filter is specified, the display creates an internal filter cache that is used along with the recording cache to provide the necessary raster info to the filter. Output is routed to the filter cache so that when the raster layer asks for the destination DC, it gets the filter cache DC. The display applies the filter when display.setFilterByRef(null). Apply receives the current background bitmap (recording cache), the opaque raster layer image (filter cache), and the destination (window). The filter knows the transparency value is 100 so it does the blending and sends the results to the window.
How do we technically make symbols and images support transparency. The view objects (Data and Layout) handle drawing maps both to output devices (windows and printers) and export files (bitmap and metafiles). All graphic elements and layers need to report whether or not they are using transparent colors. So that when the view starts to generate output, it can check if there are any transparent colors. If there are, it uses the following algorithm to produce output:
This will result in a series of bitmaps (the bands) being copied to the output device or export file. If there are no transparent colors in the map, the metafile will be generated normally, i.e., it will contain series of vector graphics.
Often times it is necessary to quickly update the display to show movement of live objects. For example, movements of commercial assets tracked by GPS. There are two aspects to the problem:
There are many ways to store and draw event data in your application. The most common methods are as follows:
Note the three common ways to store custom data:
The best choice depends on where in the drawing order your events need to draw, whether you want to use standard rendering objects, and whether or not you need to support a proprietary data format.
In all cases, the standard Invalidation model of drawing should be used. That is, create an object that draws (i.e., layer, graphic element, or event handler), plug it into your map, and call IActiveView.partialRefresh when you want it to draw.
At version 9 of ArcObjects, a new interface, IViewRefresh makes it simpler to quickly refresh the display to show live objects. Clients should use the animationRefresh routine in place of partialRefresh to invalidate their custom drawing object. For example, you may store “live” features using a layer with its own display cache. Animation is accomplished by moving features, invalidating the layer (with animationRefresh), and letting redraw happen naturally. When animationRefresh is used instead of partialRefresh, the following optimizations / tradeoffs are enabled:
Text Anti-aliasing is temporarily disabled. This prevents labels from having to be redrawn every time the animation layer is invalidated. Remember that anti-aliased text uses the background as part of its rendering so normally when anything below it changes, the text also needs to draw from scratch.
Transparent layers above the animation layer are not automatically invalidated along with the animation layer. This speeds up the redraw with the following limitation: Features in the animation layer will no longer show through the transparent layer above it.
All drawing is directed to the recording cache HDC rather than the window. This causes all drawing to happen behind the scenes. When drawing is complete, the window is updated once from the completed recording cache. The result is less flashing.
To avoid excessive CPU consumption during rapid drawing you can make a call to UpdateWindow between invalidating old location and invalidating new location.
Private m_pScreenDisplay As IScreenDisplay ScreenDisplay screenDisplay = new ScreenDisplay();
SimpleFillSymbol symbol = new SimpleFillSymbol();
Envelope env = new Envelope();
env.putCoords(0,0,50,50);
screenDisplay.getDisplayTransformation().setBounds(env);
screenDisplay.getDisplayTransformation().setVisibleBounds(env);
public Polygon getPolygon(){
try{
Polygon polygon = new Polygon();
Point point = new Point();
point.putCoords(20,20);
polygon.addPoint(point,null,null);
point.putCoords(30,20);
polygon.addPoint(point,null,null);
point.putCoords(30,20);
polygon.addPoint(point,null,null);
point.putCoords(20,30);
polygon.addPoint(point,null,null);
polygon.close();
return polygon;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
public void myDraw(IDisplay display, int hDC){
try{
SimpleFillSymbol symbol = new SimpleFillSymbol();
IDraw draw = (IDraw)display;
draw.startDrawing(hDC, (short)esriScreenCache.esriNoScreenCache);
Polygon polygon = getPolygon();
draw.setSymbol(symbol);
draw.draw(polygon);
draw.finishDrawing();
}catch(Exception e){
e.printStackTrace();
}
}
public void picturePaint(){
myDraw(screenDisplay, Picture1.gethDC());
}
public void picturePaint(){
try{
if(screenDisplay.isCacheDirty((short)esriScreenCache.esriScreenRecording)){
screenDisplay.startRecording();
myDraw(screenDisplay, Picture1.gethDC());
screenDisplay.stopRecording();
}
else{
screenDisplay.drawCache(Picture1.gethDC(), esriScreenCache.esriScreenRecording, null, null);
}
}catch(Exception e){
e.printStackTrace();
}
}
screenDisplay.invalidate(null, true, (short)esriScreenCache.esriScreenRecording);
int cacheID;
cacheID = screenDisplay.addCache();
public void actionPerformed(java.awt.event.ActionEvent e){
IEnvelope env = screenDisplay.getDisplayTransformation().getVisibleBounds();
env.expand(0.75, 0.75, true);
screenDisplay.getDisplayTransformation().setVisibleBounds(env);
screenDisplay.invalidate(null, true, esriScreenCache.esriAllScreenCaches);
}
Very advanced drawing effects, such as color transparency, can be accomplished using display filters. Filters work along with a display cache to allow a rasterized version of your drawing to be manipulated. When a filter is specified to the display (using IDisplay.setFilterByRef), the display creates an internal filter cache that is used along with the recording cache to provide raster info to the filter. Output is routed to the filter cache until the filter is cleared (that is, setFilterByRef(null)). At that point, the display calls IDisplayFilter.apply. apply receives the current background bitmap (recording cache), the drawing cache (containing all of the drawing that happened since the filter was specified), and the destination HDC. The transparency filter performs alpha blending on these bitmaps and draws them to the destination HDC to achieve color transparency. New filters can be created to realize other effects.

Color is used in many places in ArcGIS applicationsin feature and graphics symbols, as properties set in renderers, as the background for ArcMap or ArcCatalog windows, and as properties of a raster image. The type of color model used in each of these circumstances will vary. For example, a window background would be defined in terms of an RGB color because display monitors are based on the RGB model. A map made ready for offset-press publication could have CMYK colors to match printer's inks.
Color can be represented using a number of different models, which often reflect the ways in which colors can be created in the real world.You may be familiar with the RGB color model, which is based on the primary colors of lightred, green, and blue. When red, green, and blue rays of light coincide, white light is created. The RGB color model is therefore termed additive, as adding the components together creates light. By displaying pixels of red, green, and blue light, your computer monitor is able to portray hundreds, thousands, and even millions of different colors. To define a color as an RGB value, you give a separate value to the red, green, and blue components of the light. A value of 0 indicates no light, and 255 indicates the maximum light intensity.

Red, green, blue (RGB) color model
Here are a few rules for RGB values:
Another common way to represent color, the CMYK model, is modeled on the creation of colors by spot printing. Cyan, magenta, yellow, and black inks are mingled on paper to create new colors. The CMYK model, unlike RGB, is termed subtractive, as adding all the components together creates an absence of light (black).
Cyan, magenta, yellow (CMY) color model
Cyan, magenta, and yellow are the primary colors of pigmentsin theory you can create any color by mixing different amounts of cyan, magenta, and yellow. In practice, you also need black, which adds definition to darker colors and is better for creating precise black lines. HSV, or the hue, saturation, and value color model, describes colors based around a color wheel that arranges colors in a spectrum. The hue value indicates where the color lies on this color wheel and is given in degrees. For example, a color with a hue of 0 will be a shade of red, whereas a hue of 180 will indicate a shade of cyan.

Color wheel for hue, saturation, and value (HSV) color model
Saturation describes the purity of a color. Saturation ranges from 0 to 100; therefore, a saturation of 20 would indicate a neutral shade, whereas a saturation of 100 would indicate the strongest, brightest color possible. The value of a color determines its brightness, with a range of 0 to 100. A value of 0 always indicates black; however, a value of 100 does not indicate white, it just indicates the brightest color possible. Hue is simple to understand, but saturation and value can be confusing. It may help to remember these rules:
The HLS, or hue, lightness, and saturation model, has similarities with the HSV model. Hue again is based on the spectrum color wheel, with a value of 0 to 360. Saturation again indicates the purity of a color, from 0 to 100. However, instead of value, a lightness indicator is used, again with a range of 0 to 100. If lightness is 100, white is produced, and if lightness is 0, black is produced. The last color model is grayscale. 256 shades of pure gray are indicated by a single value. A grayscale value of 0 indicates black, and a value of 255 indicates white.

Grayscale color model
The CIELAB color model is used internally by ArcObjects, as it is device independent. The model, based on a theory known as opponent process theory, describes color in terms of three “opponent channels”. The first channel, known as the 1 channel, traverses from black to white. The second, or 2 channel, traverses red to green hues. The last channel, or 3 channel, traverses hues from blue to yellow.

Sample Color Values
Objects that support the IColor interface allow precise control over any color used within the ArcObjects model. You can get and set colors using a variety of standard color modelsRGB, CMYK, HSV, HLS, and Grayscale.
The properties available on the IColor interface define the common functionality of all color objects. Representations of colors are held internally as CIELAB colors, described in the color theory topic. The CIELAB color model is device independent, providing a frame of reference to allow faithful translation of colors between one color model and another. You can use the getCIELAB and setCIELAB methods of the IColor interface to interact directly with a color object using the CIELAB model.Although colors are held internally as CIELAB colors, you don't need to deal directly with the CIELAB color modelyou can use the IColor interface to simply read and define colors. Or, you could use the following function, which essentially performs the same action but lets you see how the conversion is performed.
![]()
public int getRGB(int red, int blue, int green){
int RGB = red + (100 * green) + (10000 * blue);
return RGB;
}
One important point to note when reading the RGB property: the useWindowsDithering property should generally be set to true. If useWindowsDithering is false, the RGB property returns a number with a high byte of 2, indicating the use of a system color, and the RGB property will return a value outside of the range you would expect. If you write to the RGB property, the useWindowsDithering property will be set to true for you. For more information on converting individual byte values to long integer representation, look for topics on color models and hexadecimal numbering in your development environment's online Help system. The IColor interface also provides access to colors through another color modelCMYK. The CMYK property can be used in a similar way as RGB to read or write a Long integer representing the cyan, magenta, yellow, and black components of a particular colorthe difference being that the CMYK color model requires four values to define a color.
public int convertCMYKToInt(long black, long yellow, long magenta, long cyan){
int value = black + (100 * yellow) + (10000 * magenta) + (1000000 * cyan);
return value;
}
ColorRamps are used in two different ways in ArcObjects: by accessing the individual colors in a ramp or by using the ramp object directly as a property or, in a method, of another object. First, a color ramp can be set up and its individual colors accessed. For example, when a UniqueValueRenderer is created, each symbol in its symbol array should be set individually, perhaps using colors from a color ramp. To retrieve individual colors from a color ramp, first set the Size property according to the number of Color objects you wish to retrieve from the ramp. The CreateRamp method should then be called, which populates both the Color and the Colors properties. The Color property holds a read-only, zero-based array of Color objects, returned by index. The code fragment below shows the creation of a RandomColorRamp and the generation of 10 color objects from that ramp. Note that the Boolean parameter used in the CreateRamp method is checked after the method is called to ensure the colors were generated correctly.
![]()
RandomColorRamp colorRamp = new RandomColorRamp();
colorRamp.setSize(10);
boolean[] state = new boolean[1];
colorRamp.createRamp(state);
if(state[0]){
for(int i=0;i<colorRamp.getSize();i++){
//Access the color array here and et the colors
//for an array of synbols or map layers
}
}
AlgorithmicColorRamp algoRamp = new AlgorithmicColorRamp();
algoRamp.setFromColor(myFromColor);
algoRamp.setToColor(myToColor);
GradientFillSymbol symbol = new GradientFillSymbol();
symbol.setColorRamp(algoRamp);
symbol.setIntervalCount(5);
The setupDC, draw, and resetDC methods can be used in conjunction with the ROP2 property to draw a symbol to a device context, providing a familiar procedure for those who have worked with device context drawing before. Calling the setupDC method selects the Symbol into the specified DC, and setting the ROP2 property to one of the esriRaster-OpCodes specifies how the Symbol is drawn (see below). Subsequently calling the draw method will draw the Symbol, using the Geometry parameter from the Draw method, to the DC. The following code demonstrates drawing to a device context, where pDisplay is a valid Display object, pPoint is a valid Point in display coordinates, and pSymbol is any valid Symbol. There are two important points to note:
![]()
screenDisplay.startDrawing(screenDisplay.getHDC(), (short)esriScreenCache.esriNoScreenCache);
symbol.setupDC(screenDisplay.getHDC(), screenDisplay.getDisplayTransformation());
symbol.draw(point);
symbol.resetDC();
screenDisplay.finishDrawing();
You can use symbol level drawing to alter the draw order of features within feature layers. By using symbol level drawing you can control the draw order of features on a symbol by symbol basis. This means that features do not necessarily need to be drawn in the same order that feature layers appear in the table of contents. With symbol level drawing you can control when a feature draws by controlling when the feature's symbol draws. Furthermore, when multi layer symbols are used, you can control the drawing order of individual symbol layers.
Using symbol level drawing is most useful for maps with cased lines because it can be used to create overpass and underpass effects where the line features cross, which is a good way to show connectivity. Symbol level drawing can be used to achieve other advanced effects as well.
IMapLevel is the interface that you use to assign a map level (or levels if the symbol is multi layer) to a symbol, thus preparing it to be used with symbol level drawing. Not all symbols support this interface. Note that if you assign a symbol with map levels to a graphic element, then the levels will be ignored. Also, ISymbol.draw ignores levels as well.
(1) Turn on symbol level drawing, either for a layer using ISymbolLevels.useSymbolLevels, or for your entire map using IMap.setUseSymbolLevels.
(2) For each layer in your map that you want to use symbol levels for, access the layer's renderer using IGeoFeatureLayer.getRenderer.
(3) Access your layer's symbols through the renderer.
(4) Using IMapLevel, set symbol levels on your layer's symbols. Symbols with MapLevel = 0 draw first, then symbols with MapLevel = 1, continuing until the highest MapLevel is reached. If two symbols have the same MapLevel, then the features drawn with these symbols are drawn in the normal layer order. A MapLevel of -1 for a multilayer symbol (MultiLayerMarkerSymbol, MultiLayerLineSymbol, MultiLayerFillSymbol) indicates that each of the symbol's individual layers are drawn with their individual MapLevel .
Symbol Level Drawing dialog
Join and Merge
In both of the dialogs above, Join and Merge are GUI terms ued to help users set up symbol levels. See the ArcGIS Desktop Help for more information. The graphics below show the effect of joining a symbol, which makes features with the same symbol appear to 'connect' to each other. Merge makes features with different symbols appear to 'connect'. Both of these effects are implemented behind the scenes using the symbol level objects and interfaces. You can toggle symbol level drawing on or off, either using ISymbolLevels.setUseSymbolLevels for a layer, or for an .mxd built in ArcGIS 8.3 or earlier, for your entire map using IMap.setUseSymbolLevels.

Symbols drawing using Map Levels
The following code turns on symbol level drawing for the layer in the map and sets up the multi-layer symbol assigned to this layer to be joined.
//...
if(map.getLayer(0) instanceof IGeoFeatureLayer){
IGeoFeatureLayer layer = (IGeoFeatureLayer)map.getLayer(0);
ISymbolLevels levels = (ISymbolLevels)layer;
levels.setUseSymbolLevels(true);
if(renderer.getSymbol() instanceof IMultiLayerLineSymbol){
IMultiLayerLineSymbol multi = (IMultiLayerLineSymbol)renderer.getSymbol();
setMapLevel((IMapLevel)multi,-1);
for(int i=0;i<multi.getLayerCount();i++)
setMapLevel((IMapLevel)multi.getLayer(i),multi.getLayerCount()-(i+1));
}
}
//... public void setMapLevel(IMapLevel level, int i) {
if(level != null){
try {
level.setMapLevel(i);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Marker Symbols

The IMarkerSymbol interface represents the properties all types of MarkerSymbol have in common. These are Angle, Color, Size XOffset, and YOffset.
IMarkerSymbol is the primary interface for all marker symbols. All other marker symbol interfaces inherit the properties and methods of IMarkerSymbol. The interface has five read_write properties that allow you to get and set the basic properties of any MarkerSymbol. The Color property can be set to any IColor object, and its effects will be dependent on the type of coclass you are using.

Marker Symbol Color Properties
The Size property sets the overall height of the symbol if the symbol is a SimpleMarkerSymbol, CharacterMarkerSymbol, PictureMarkerSymbol, or MultiLayerMarkerSymbol. For an ArrowMarkerSymbol, setSize sets the length. The units are points. The default size is eight for all marker symbols except the PictureMarkerSymbolits default size is 12. The Angle property sets the angle in degrees to which the symbol is rotated counterclockwise from the horizontal axis; and its default is 0. The XOffset and YOffset properties determine the distance to which the symbol is drawn offset from the actual location of the feature. The properties are both in printer's points, both have a default of zero, and both can be negative or positive; positive numbers indicate an offset above and to the right of the feature, and negative numbers indicate an offset below and to the left. Below, you create an ArrowMarkerSymbol and set only the properties inherited from IMarkerSymbol.
ArrowMarkerSymbol arrow = new ArrowMarkerSymbol();
arrow.setAngle(60);
arrow.setSize(50);
arrow.setXOffset(20);
arrow.setYOffset(30);
arrow.setColor(myColor)
The size, XOffset, and YOffset of a marker symbol is in printer's points1/72 of an inch.

The types of marker symbols
The rotation of a marker symbol is specified in mathematical notation.

Marker Symbol Rotation
Below are some examples of each of the marker symbol types.

Simple marker symbols

Arrow marker symbols

Character marker symbols

Picture marker symbols

Multilayer marker symbols

ILineSymbol is the primary interface for all line symbols, which all inherit the properties and methods of ILineSymbol. The interface has two read_write properties that allow you to get and set the basic properties of any line symbol. The Color property controls the color of the basic line (it does not affect any line decoration that may be presentsee the ILineProperties interface) and can be set to any IColor object. The Color property is set to black by default except for the SimpleLineSymbol, which has a default of mid-gray. The Width property sets the overall width of a line, and its units are points. Note that for a HashLineSymbol, the Width property sets the length of each hashsee HashLineSymbol for more information. The default width is 1 for all line symbols except MarkerLineSymbol, which has a default width of 8.

Types of Line Symbol
A line symbol represents how a one-dimensional feature or graphic is drawn. Straight lines, polylines, curves, and outlines can all be drawn with a line symbol. There are five different types of line symbols you can use.
Line Symbol Width
The width of a line symbol is in printer's pointsabout 1/72 of an inch.

The IFillSymbol interface, inherited by all the specialist fill symbols in ArcObjects, has two read_write properties. The Color property controls the color of the basic fill as described below and can be set to any IColor object.

Fill Symbol Default Colors
The Outline property sets an ILineSymbol object, which is drawn as the outline of the fill symbol. By default, the outline is a solid SimpleLineSymbol, but you can use any type of line symbol as your outline. Note that the outline is centered on the boundary of the feature; therefore, an outline with a width of 5 will overlap the fill symbol by a visible amount.

Types Of Fill Symbols

A fill symbol specifies how the area and outline of any polygon is to be drawn.

The ITextSymbol interface is the primary interface for defining the characteristics of a text and is inherited by the ISimpleTextSymbol and IFormattedTextSymbol interfaces and therefore may not need to be declared specifically. It contains the Font property, which is the first logical step to defining a new TextSymbol. To set a Font, you should first create a COM font object. Using the IFontDisp interface of your font, you should set the Name of the font. You should also set whether or not your IFontDisp is italic, bold, strike-through, or underlined and set its CharacterSet and weight.
![]()
StdFont font = new StdFont();
font.setName("ESRI Cartography");
font.setBold(true);
Each font may include different character sets to allow for different alphabets and symbology. For most applications, you won't need to swap character sets from the default. The StdFont object is defined in the stdole2.tlb type library. Other development environments provide a similar implementation. If no generic Font class is available the esriSystemUI.SystemFont class can be used - it provides similar functionality to tht of the stdole2.Font class. If the TextSymbol is used to draw text to a point, not along a line (see TextPath), you can use the Angle property to rotate the text string. The Angle property specifies the angle of the text baseline, in degrees from the horizontal, and defaults to zero. For Hebrew and Arabic fonts, set the RightToLeft property to True to lay the text string out in a right-to-left reading order. For any existing TextSymbol, the actual size in x and y directions can be calculated using the GetTextSize method. Having set a Size that defines the font height, the GetTextSize method will calculate the actual height and length of the symbol in points. Note that the GetTextSize method ignores the TextPath property if it is set through the ISimpleTextSymbol interface. GetTextSize is useful for calculating text placements on a PageLayout or whether a text string should be truncated to fit within a certain space. The use of this method is shown below, where pDisplay is the IDisplay of the PageLayout or Map that the TextSymbol belongs to, and pTextSymbol is a valid TextSymbol. Note that the StartDrawing and FinishDrawing calls are necessary to make sure the hDC of the display is valid. The dblX and dblY variables are populated respectively with the height and length of the text parameter when drawn with the pTextSymbol symbol.
![]()
double[] x={0};
double[] y={0};
screenDisplay.startDrawing(0, (short)esriScreenCache.esriNoScreenCache);
textSymbol.getTextSize(display.getHDC(),display.getDisplayTransformation(),"My Text",x,y);
screenDisplay.finishDrawing();
3DChartSymbol is an abstraction of the three types of chart symbol. It represents a marker symbol, which can be used by a ChartRenderer to symbolize geographical data by multiple attributes. Although they are generally used by a ChartRenderer, if all the properties are set appropriately you can also use the symbol as a MarkerSymbol to symbolize an individual Feature or Element. The following sections describe how to set up the different coclasses that implement I3DChartSymbol. For more information on using these coclasses as part of a ChartRenderer, see the sections on feature renderers in this chapter.
IChartSymbol is used to calculate the size of bars or pie slices in a chart symbol. The maximum attribute value that can be represented on the chart is used to scale the other attribute values in a chart. You should always set this property when creating a 3DChartSymbol. When creating a ChartRenderer, you should have access to the statistics of your FeatureClassyou can use these statistics to set the MaxValue property to the maximum value of the attribute or attributes being rendered. For example, if there are two fields rendered with a chart symbol, one containing attribute values from 0 to 5 and one containing attribute values from 0 to 10, set MaxValue to 10.
![]()
BarChartSymbol symbol = new BarChartSymbol();
symbol.setMaxValue(10);

The IDisplayFeedback interface is used to define the common operations on all of the display feedback operations. These include moving, symbolizing, and refreshing the display feedbacks as well as setting a display feedback object's Display property (for example, setting it to IActiveView.getScreenDisplay). The IDisplayFeedback interface is useful only in combination with one of the display feedback objects and its derived interfaces, for example, the NewPolygonFeedback object and its INewPolygonFeedback interface. Nearly all of the display feedback interfaces employ interface inheritance from IDisplayFeedback; hence, there is no need to use QueryInterface to access its methods and properties. Typically, the Display and Symbol properties would be set when a display feedback object is initialized, while the MoveTo method would be called in a mouse move event. Setting the Symbol property is optional. If not set, a default symbol is used. The Refresh method is used to redraw the feedback after the window has been refreshed (for example, when it is activated again), and it should be called in response to the Tool's Refresh event. The hDC parameter, which is required by the Refresh method, is actually passed into the subroutine for you. In the following example, a check is first made to see if polyFeedback, which is a member variable NewPolygonFeedback object, has been instantiated yet, that is, if the user is currently using the feedback. If it has been instantiated, then the refresh method is called.
![]()
public void refresh(int hDC){
If (polygonFeedback != null)
polyFeedback.refresh(hDC)
}
The following code example shows how to use the IDisplayFeedback interface with the INewEnvelopeFeedback interface to create a display feedback that will allow the user to add a new polygon. Note that this code simply demonstrates the visual feedback; further code is required if you wish to add that drawn shape as a map element or feature. The new envelope feedback object is declared as a member variable as follows:
INewEnvelopeFeedback newEnvFeed;
Other objects are locally declaredenv as IEnvelope, screenDisplay as IScreenDisplay, lineSym as ISimpleLineSymbol, and startPoint and movePoint as IPoint. The following code would be placed in the onMouseDown event to set up the Display and Symbol properties and to call INewEnvelopeFeedback.start with the current mouse location in map units.
NewEnvelopeFeedback newEnvFeed = new NewEnvelopeFeedback(); newEnvFeed.setDisplayByRef(screenDisplay);
newEnvFeed.setSymbolByRef(ineSym);
newEnvFeed.start(startPoint);
newEnvFeed.moveTo(movePoint);
env = newEnvFeed.stop();

The IRubberband interface has two methods, trackExisting and trackNew, which are used to move existing geometries and create new geometries, respectively. These methods would normally be called from within the code for a tool's onMouseDown event, and they would then handle all subsequent mouse events themselves. They would capture subsequent mouse and keyboard events, such as onMouseMove, onMouseUp, and KeyDown events, and would complete when they received a onMouseUp event or abort if the Esc key was pressed. Because the events are being trapped by the rubberband objects. This means that very little code is required to use them, although this comes at the expense of flexibility. Typically, these objects would be used for simple tasks such as dragging a rectangle or creating a new line. Operations that involve moving the vertices of existing geometries would require the feedback objects to be used instead. The trackNew method takes two parameters: an IScreenDisplay object representing the ScreenDisplay to draw the Rubberband and an ISymbol object to use for drawing the rubberband. If no symbol is given, then the default symbol is used. The method returns a new geometry objectthe type of geometry returned depends on which class was used. RubberPolygon class returns a Polygon object. If the method fails to complete (that is, if the user presses the Esc key), then Nothing is returned. The types of geometry that are returned for TrackNew by each of the rubber objects are as follows:
![]()
public void onMouseDown(int button, int shift, int x, int y) {
super.onMouseDown(button, shift, x, y);
try {
IMap map = hookHelper.getFocusMap();
//Create new RubberLine
RubberLine rubberLine = new RubberLine();
//Track a new Polyline on current document's display using default symbol
IGeometry geom = rubberLine.trackNew(hookHelper.getActiveView().getScreenDisplay(), null);
} catch (Exception e) {
e.printStackTrace();
}
}
The trackExisting method also takes ScreenDisplay and Symbol parameters as well as an IGeometry representing the input Geometry. This last parameter represents the geometry to move on the screen and is passed by reference so that it may be altered by the rubberband operation. The method returns a Boolean, which will be True unless the operation was interrupted by the user pressing the Esc key. The method will do nothing if the Geometry that is passed in does not intersect the current mouse location. The types of geometry that are expected by trackExisting for each of the rubber objects are as follows:
public void onMouseDown(int button, int shift, int x, int y) {
super.onMouseDown(button, shift, x, y);
try {
IMap map = hookHelper.getFocusMap();
//Create new RubberPolygon object
RubberPolygon rubberPolygon = new RubberPolygon();
//Move an exisiting polygon using the default symbol
IGeometry geom = rubberPolygon.trackExisting(hookHelper.getActiveView().getScreenDisplay(), null, geom);
} catch (Exception e) {
e.printStackTrace();
}
}
The PointTracker object is not currently useful. Moving and resizing of point elements is handled by envelope trackers, the size of the envelope corresponding to the symbolized point. Although the selection trackers are coclasses, you would only cocreate one if you were building your own custom element when implementing IElement.selectionTracker
.![]()
![]()
![]()
The envelope tracker operates on all element type
![]()
![]()
The line tracker and polygon tracker lets the user manipulate the vertices of polylines and polygons.
![]()
The callout tracker lets the user manipulate text callouts.
The ISelectionTracker interface controls the selection handle user interface. You might use ISelectionTracker in order to provide different behavior, for example, the Element Movement tool that snaps elements to a grid. However, it is more likely that you will use this interface when building a custom object such as an element. You can gain access to selection trackers with IElement.getSelectionTracker, IElementEditVertices.getMoveVerticesSelectionTracker, or IGraphicsContainerSelect.getSelectionTracker. When using IElement, you will get either an envelope tracker or edit vertices tracker, depending on the state of the element. This code example ensures that an envelope tracker is returnedif the element has a vertex edit tracker, it is changed to a envelope tracker and the document is refreshed.
![]()
public void ensureEnvelopeTracker(IActiveView activeView, IElement element){
try {
IScreenDisplay display = activeView.getScreenDisplay();
if(element instanceof IElementEditVertices){
IElementEditVertices editVertices = (IElementEditVertices)element;
if(editVertices.isMovingVertices()){
editVertices.setMovingVertices(false);
activeView.partialRefresh(esriViewDrawPhase.esriViewGeography, null,element.getSelectionTracker().getBounds(display));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
After obtaining a reference to a selection tracker, always set the Display property before using it. The Geometry property of a selection tracker applies to the tracker, not the element: for envelope trackers, the geometry is a polygon created from the envelope shape; for vertex edit trackers, the geometry is a polygon or polyline as appropriate. The Geometry property is updated when the user finishes reshaping the element with the selection tracker. The hitTest method provides information about the position of the mouse. The returned values are defined by esriTrackerLocation: The enumeration names are most relevant to envelope trackers, but hitTest can also be used with vertex edit trackers and callout trackers. In these cases, the returned values are LocationNone, LocationInterior, and LocationTopLeft. Many of the ISelectionTracker methodsfor example, onMouseDowncorrespond to user interface events. When controlling a selection tracker with a user interface tool, pass on the tool events to the selection tracker.
queryMoveFeedback and queryResizeFeedback return the feedback objects that the selection tracker is using. draw is called by ArcObjects if the element is selected, so normally you do not need to use this method (though it is important if you implement your own custom selection tracker).The CancelTracker object is the favorite class of many users, though most probably don't realize it. Have you ever started a process and realized as soon as you did that it wasn't what you wanted? If the process employed the CancelTracker object, then you would be able to hit the escape key and halt the process before it had completed. The CancelTracker object is the object used by ArcObjects to monitor the Esc key (optionally, the space bar and mouse clicks as well) and terminate processes at the request of the user. A CancelTracker is typically handed into or created just prior to functions that execute a lengthy operation. Just before such operations begin, ITrackCancel.reset must be called; Reset sets the state of the CancelTracker to uncancelled and returns the internal counter, which is used to update progression to zero. Within the innermost loop of the operation, ITrackCancel.continue should be called to check whether the user has canceled the operation. By default, a cancellation occurs under the following circumstances:
CancelTracker cancel = new CancelTracker(); activeView.output <OLE_handle>, <screen resolution>, <pixel bounds>, <visible bounds>, pCancel
In this case, you can provide cancel capabilities by simply creating a CancelTracker object and passing it in to the output method. The output method will then take care of monitoring the Esc button and canceling the process if the user chooses to. Another way to use a CancelTracker object is similar to the process above, but you as the developer are responsible for monitoring the object. An approach of this type would be used when the execution of your code could take a considerable amount of time and you want to give the user the option of canceling out of the process. The following Java code demonstrates this process. The code is designed to loop through a set of selected network features and run the Connect method on them to ensure they are connected to the network. The CancelTracker object is included for aborting the process if the user accidentally selects too many features or just wants the process to stop.
public void testCancel(IEnumFeature enumFeats, CancelTracker cancel){
try {
IFeature feature = enumFeats.next();
while(feature != null){
if(feature instanceof INetworkFeature)
((INetworkFeature)feature).connect();
if(!cancel.esri_continue()){
JOptionPane.showConfirmDialog(null, "Process has been cancelled!");
}
feature = enumFeats.next();
}
} catch (Exception e) {
e.printStackTrace();
}
}