Layer display settings

Download Sample Viewer

Description

This sample shows how to update the opacity, brightness, contrast, and gamma values of an ArcGISLocalTiledLayer or ArcGISLocalDynamicMapServiceLayer. The values can be updated via sliders. Slider values are automatically updated with the current brightness, contrast, and gamma values from the tiled or dynamic layer when the layer is selected.

Code snippet


  // set the opacity for the tiled layer to 0.75 (default is 1.0, fully opaque)
  tiledLayer.setOpacity(0.75f);
  
  // set the contrast for the tiled layer to 50 (default is 0)
  tiledLayer.setContrast(50);
  
  // set the brightness for the dynamic layer to -25 (default is 0)
  dynamicLayer.setBrightness(-25);
  
  // set the gamma for the dynamic layer to 10 (default is 0)
  dynamicLayer.setGamma(10);
  
  

Sample Code

/* Copyright 2014 Esri

All rights reserved under the copyright laws of the United States
and applicable international laws, treaties, and conventions.

You may freely redistribute and use this sample code, with or
without modification, provided you include the original copyright
notice and use restrictions.

See the use restrictions.*/
package com.esri.client.samples.map;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.Hashtable;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import com.esri.client.local.ArcGISLocalDynamicMapServiceLayer;
import com.esri.client.local.ArcGISLocalTiledLayer;
import com.esri.core.geometry.Envelope;
import com.esri.map.JMap;
import com.esri.map.LayerInitializeCompleteEvent;
import com.esri.map.LayerInitializeCompleteListener;
import com.esri.map.LayerList;
import com.esri.runtime.ArcGISRuntime;

/**
 * This sample shows how to update the opacity, brightness, contrast and gamma values 
 * of a {@link ArcGISLocalTiledLayer} or {@link ArcGISLocalDynamicMapServiceLayer}.
 * The layer's opacity, brightness, contrast and gamma values can be updated via 
 * sliders.
 * <p> 
 * Slider values are automatically updated with the current opacity, brightness, 
 * contrast and gamma values from the tiled or dynamic layer when the layer is 
 * selected.
 */
public class LocalLayerSettingsApp {

  private JComponent contentPane;
  private JMap map;

  private ArcGISLocalDynamicMapServiceLayer dynamicLayer;
  private ArcGISLocalTiledLayer tiledLayer;
  private JRadioButton tiledButton;
  private JRadioButton dynamicButton;
  private JSlider opacitySlider;
  private JSlider contrastSlider;
  private JSlider brightnessSlider;
  private JSlider gammaSlider;

  // values for opacity, brighness, contrast, and gamma
  private final static int MAX_VALUE = 100;
  private final static int MIN_VALUE = -100;
  private final static int DEFAULT_VALUE = 0;
  private final static int OPACITY_FACTOR = 100;

  private String FSP = System.getProperty("file.separator");
  private Font font = new Font("Serif", Font.ITALIC, 12);

  /**
   * Default constructor
   */
  public LocalLayerSettingsApp() {
  }

  // ------------------------------------------------------------------------
  // Core functionality
  // ------------------------------------------------------------------------

  /**
   * Updates opacity, brightness, contrast, and gamma values of the sliders based on the actual layer values.
   */
  public void updateSliders() {
    if (dynamicButton.isSelected()) {
      opacitySlider.setValue((int)(dynamicLayer.getOpacity()*OPACITY_FACTOR));
      brightnessSlider.setValue((int)dynamicLayer.getBrightness());
      contrastSlider.setValue((int)dynamicLayer.getContrast());
      gammaSlider.setValue((int)dynamicLayer.getGamma());
    }
    if (tiledButton.isSelected()) {
      opacitySlider.setValue((int)(tiledLayer.getOpacity()*OPACITY_FACTOR));
      brightnessSlider.setValue((int)tiledLayer.getBrightness());
      contrastSlider.setValue((int)tiledLayer.getContrast());
      gammaSlider.setValue((int)tiledLayer.getGamma());
    }
  }

  /**
   * Update the selected layer's opacity, brightness, contrast, or gamma based on the slider value.
   * 
   * @param source a slider.
   */
  public void updateLayers(JSlider source) {
    if (source.getName().equals("Opacity")) {
      if (tiledButton.isSelected()) {
        tiledLayer.setOpacity((float)source.getValue()/OPACITY_FACTOR);
      } else if (dynamicButton.isSelected())
        dynamicLayer.setOpacity((float)source.getValue()/OPACITY_FACTOR);
    } else if (source.getName().equals("Contrast")) {
      if (tiledButton.isSelected()) {
        tiledLayer.setContrast(source.getValue());
      } else if (dynamicButton.isSelected())
        dynamicLayer.setContrast(source.getValue());
    } else if (source.getName().equals("Brightness")) {
      if (tiledButton.isSelected()) {
        tiledLayer.setBrightness(source.getValue());
      } else if (dynamicButton.isSelected())
        dynamicLayer.setBrightness(source.getValue());
    } else if (source.getName().equals("Gamma")) {
      if (tiledButton.isSelected()) {
        tiledLayer.setGamma(source.getValue());
      } else if (dynamicButton.isSelected())
        dynamicLayer.setGamma(source.getValue());
    }
  }

  // ------------------------------------------------------------------------
  // Public methods
  // ------------------------------------------------------------------------

  /**
   * Creates and displays the UI, including the map, for this application.
   *
   * @return the UI component.
   */
  public JComponent createUI() {

    contentPane = createContentPane();

    // sliders panel
    JPanel panel = createPanel();
    contentPane.add(panel);

    // create map
    map = createMap();
    contentPane.add(map);

    return contentPane;
  }

  // ------------------------------------------------------------------------
  // Static methods
  // ------------------------------------------------------------------------
  /**
   * Starting point of this application.
   * 
   * @param args arguments to this application.
   */
  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        try {
          // instance of this application
          LocalLayerSettingsApp app = new LocalLayerSettingsApp();

          // create the UI, including the map, for the application.
          JFrame appWindow = app.createWindow();
          appWindow.add(app.createUI());
          appWindow.setVisible(true);
        } catch (Exception e) {
          // on any error, display the stack trace.
          e.printStackTrace();
        }
      }
    });
  }

  // ------------------------------------------------------------------------
  // Private methods
  // ------------------------------------------------------------------------
  /**
   * Creates the map.
   *  
   * @return a map.
   */
  private JMap createMap() {

    final JMap jMap = new JMap();
    jMap.setExtent(new Envelope(-15000000, 2000000, -7000000, 8000000));

    // set a tiled layer as basemap
    tiledLayer = new ArcGISLocalTiledLayer(getPathSampleData() + "tpks" + FSP + "Topographic.tpk");
    final LayerList layers = jMap.getLayers();
    layers.add(tiledLayer);
    
    
    tiledLayer
        .addLayerInitializeCompleteListener(new LayerInitializeCompleteListener() {
          @Override
          public void layerInitializeComplete(LayerInitializeCompleteEvent arg0) {
            if (arg0.getID() == LayerInitializeCompleteEvent.LOCALLAYERCREATE_ERROR) {
              String errMsg = "Failed to initialize due to "
                  + tiledLayer.getInitializationError();
              JOptionPane.showMessageDialog(jMap, wrap(errMsg), "",
                  JOptionPane.ERROR_MESSAGE);
            }
          }
        });

    // create the dynamic layer and add to map
    dynamicLayer = new ArcGISLocalDynamicMapServiceLayer(getPathSampleData() + "mpks" + FSP + "USCitiesStates.mpk");
    layers.add(dynamicLayer);
    
    dynamicLayer
        .addLayerInitializeCompleteListener(new LayerInitializeCompleteListener() {
          @Override
          public void layerInitializeComplete(LayerInitializeCompleteEvent arg0) {
            if (arg0.getID() == LayerInitializeCompleteEvent.LOCALLAYERCREATE_ERROR) {
              String errMsg = "Failed to initialize due to "
                  + dynamicLayer.getInitializationError();
              JOptionPane.showMessageDialog(jMap, wrap(errMsg), "",
                  JOptionPane.ERROR_MESSAGE);
            }
          }
        });

    return jMap;
  }

  /**
   * Creates a JPanel with the user controls (button and sliders).
   *  
   * @return a panel.
   */
  private JPanel createPanel() {

    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout(FlowLayout.CENTER));
    panel.setSize(265, 350);
    panel.setLocation(10, 10);

    // create contrast slider
    opacitySlider = new JSlider(SwingConstants.HORIZONTAL, DEFAULT_VALUE, 
        MAX_VALUE, MAX_VALUE);

    // create contrast slider
    contrastSlider = new JSlider(SwingConstants.HORIZONTAL, MIN_VALUE, 
        MAX_VALUE, DEFAULT_VALUE);

    // create brightness slider
    brightnessSlider = new JSlider(SwingConstants.HORIZONTAL, MIN_VALUE,
        MAX_VALUE, DEFAULT_VALUE);

    // create gamma slider
    gammaSlider = new JSlider(SwingConstants.HORIZONTAL, MIN_VALUE,
        MAX_VALUE, DEFAULT_VALUE);


    // set sliders names
    opacitySlider.setName("Opacity");
    contrastSlider.setName("Contrast");
    brightnessSlider.setName("Brightness");
    gammaSlider.setName("Gamma");

    // Listen to the opacity slider
    opacitySlider.addChangeListener(new ChangeListener() {
      @Override
      public void stateChanged(ChangeEvent e) {
        JSlider source = (JSlider) e.getSource();
        if (!source.getValueIsAdjusting()) {
          updateLayers(source);
        }
      }
    });

    // Listen to the contrast slider
    contrastSlider.addChangeListener(new ChangeListener() {
      @Override
      public void stateChanged(ChangeEvent e) {
        JSlider source = (JSlider) e.getSource();
        if (!source.getValueIsAdjusting()) {
          updateLayers(source);
        }
      }
    });

    // Listen to the brightness slider
    brightnessSlider.addChangeListener(new ChangeListener() {
      @Override
      public void stateChanged(ChangeEvent e) {
        JSlider source = (JSlider) e.getSource();
        if (!source.getValueIsAdjusting()) {
          updateLayers(source);
        }
      }
    });

    // Listen to the gamma slider
    gammaSlider.addChangeListener(new ChangeListener() {
      @Override
      public void stateChanged(ChangeEvent e) {
        JSlider source = (JSlider) e.getSource();
        if (!source.getValueIsAdjusting()) {
          updateLayers(source);
        }
      }
    });

    // create the opacity label table
    Hashtable<Integer, JLabel> opacitylabelTable = new Hashtable<>();
    valuesToOpacitySlider(opacitylabelTable);
    opacitySlider.setLabelTable(opacitylabelTable);

    // create the contrast label table
    Hashtable<Integer, JLabel> contrastlabelTable = new Hashtable<>();
    valuesToSlider(contrastlabelTable);
    contrastSlider.setLabelTable(contrastlabelTable);

    // create the brightness label table
    Hashtable<Integer, JLabel> brightnesslabelTable = new Hashtable<>();
    valuesToSlider(brightnesslabelTable);
    brightnessSlider.setLabelTable(brightnesslabelTable);

    // create the gamma label table  
    Hashtable<Integer, JLabel> gammalabelTable = new Hashtable<>();
    valuesToSlider(gammalabelTable);
    gammaSlider.setLabelTable(gammalabelTable);

    // turn on labels at opacity major tick marks.
    opacitySlider.setMajorTickSpacing(50);
    opacitySlider.setPaintTicks(true);
    opacitySlider.setPaintLabels(true);
    opacitySlider.setBorder(BorderFactory.createTitledBorder("Opacity:"));

    // turn on labels at contrast major tick marks.
    contrastSlider.setMajorTickSpacing(100);
    contrastSlider.setPaintTicks(true);
    contrastSlider.setPaintLabels(true);
    contrastSlider.setBorder(BorderFactory.createTitledBorder("Contrast:"));

    // turn on labels at brightness major tick marks.
    brightnessSlider.setMajorTickSpacing(100);
    brightnessSlider.setPaintTicks(true);
    brightnessSlider.setPaintLabels(true);
    brightnessSlider.setBorder(BorderFactory.createTitledBorder("Brightness:"));

    // turn on labels at gamma major tick marks.
    gammaSlider.setMajorTickSpacing(100);
    gammaSlider.setPaintTicks(true);
    gammaSlider.setPaintLabels(true);
    gammaSlider.setBorder(BorderFactory.createTitledBorder("Gamma:"));

    // Set sliders font
    opacitySlider.setFont(font);
    brightnessSlider.setFont(font);
    contrastSlider.setFont(font);
    gammaSlider.setFont(font);

    // Create the buttons and group them together
    tiledButton = new JRadioButton("Tiled Layer", true);
    tiledButton.setName("Tiled Layer");
    dynamicButton = new JRadioButton("Dynamic Layer", false);
    dynamicButton.setName("Dynamic Layer");
    ButtonGroup bgroup = new ButtonGroup();
    bgroup.add(tiledButton);
    bgroup.add(dynamicButton);

    // Layer buttons Change Listener
    ChangeListener changeListener = new ChangeListener() {
      @Override
      public void stateChanged(ChangeEvent changEvent) {
        updateSliders();
      }
    };

    // Add change Listener to the radio buttons
    tiledButton.addChangeListener(changeListener);
    dynamicButton.addChangeListener(changeListener);

    panel.add(Box.createRigidArea(new Dimension(0, 10)));
    panel.add(tiledButton);
    panel.add(dynamicButton);
    panel.add(Box.createRigidArea(new Dimension(0, 10)));
    panel.add(opacitySlider);
    panel.add(Box.createRigidArea(new Dimension(0, 10)));
    panel.add(contrastSlider);
    panel.add(Box.createRigidArea(new Dimension(0, 10)));
    panel.add(brightnessSlider);
    panel.add(Box.createRigidArea(new Dimension(0, 10)));
    panel.add(gammaSlider);
    panel.setBorder(new LineBorder(Color.BLACK));

    return panel;
  }

  /**
   * Creates a content pane. 
   * 
   * @return a content pane.
   */
  private static JLayeredPane createContentPane() {
    JLayeredPane contentPane = new JLayeredPane();
    contentPane.setBounds(100, 100, 1000, 700);
    contentPane.setLayout(new BorderLayout(0, 0));
    contentPane.setVisible(true);
    return contentPane;
  }

  /**
   * Creates a window.
   * 
   * @return a window.
   */
  JFrame createWindow() {
    JFrame window = new JFrame("Opacity, Brightness, Contrast and Gamma Application");
    window.setBounds(100, 100, 1000, 700);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().setLayout(new BorderLayout(0, 0));
    window.addWindowListener(new WindowAdapter() {
      @Override
      public void windowClosing(WindowEvent windowEvent) {
        super.windowClosing(windowEvent);
        map.dispose();
      }
    });
    return window;
  }

  /**
   * Sets values for the brightness, contrast and gamma slider tables.
   *
   * @param table to set the slider range of values 
   */
  private void valuesToSlider(Hashtable<Integer, JLabel> table) {
    table.put(new Integer(MIN_VALUE), 
        new JLabel(Integer.toString(MIN_VALUE)));
    table.put(new Integer(DEFAULT_VALUE),
        new JLabel(Integer.toString(DEFAULT_VALUE)));
    table.put(new Integer(MAX_VALUE),
        new JLabel(Integer.toString(MAX_VALUE)));
  }

  /**
   * Sets values for the opacity slider table.
   *
   * @param table to set the opacity slider range of values 
   */
  private void valuesToOpacitySlider(Hashtable<Integer, JLabel> table) {
    table.put(new Integer(100), new JLabel("1"));   
    table.put(new Integer(50), new JLabel("0.5"));   
    table.put(new Integer(0), new JLabel("0"));  
  }

  private String getPathSampleData() {
    String dataPath = null;
    String javaPath = ArcGISRuntime.getInstallDirectory();
    if (javaPath != null) {
      if (!(javaPath.endsWith("/") || javaPath.endsWith("\\"))) {
        javaPath += FSP;
      }
      dataPath = javaPath + "sdk" + FSP + "samples" + FSP + "data" + FSP;
    }
    File dataFile = new File(dataPath);
    if (!dataFile.exists()) {
      dataPath = ".." + FSP + "data" + FSP;
    }
    return dataPath;
  }
  
  private String wrap(String str) {
    // create a HTML string that wraps text when longer
    return "<html><p style='width:200px;'>" + str + "</html>";
  }
}
Feedback on this topic?