Styling a layer with SLD is a two-step process:
-
Convert an SLD definition to a Java domain object (
TLcdSLDFeatureTypeStyle
) -
Apply that styling to the layer
This tutorial offers examples of the most common use cases for completing those two steps. For more detail about the concepts and API, see The SLD styling model.
Decoding an SLD file
To convert an SLD file containing the XML-encoded version of the SLD styling to a Java domain object, you can use the TLcdSLDFeatureTypeStyleDecoder.decode
method.
TLcdSLDFeatureTypeStyleDecoder decoder = new TLcdSLDFeatureTypeStyleDecoder();
String sldFile = "Data/Shp/Usa/rivers.sld";
TLcdSLDFeatureTypeStyle sldStyle = decoder.decodeFeatureTypeStyle(sldFile);
If the SLD is not stored in a file, you can either decode directly from an InputStream
, or use the static utility method to decode directly from a String
.
For example:
InputStream
TLcdSLDFeatureTypeStyleDecoder decoder = new TLcdSLDFeatureTypeStyleDecoder();
try (InputStream is = new TLcdInputStreamFactory().createInputStream("Data/Shp/Usa/rivers.sld")) {
TLcdSLDFeatureTypeStyle sldStyle = decoder.decodeFeatureTypeStyle(is);
}
String
String sldAsString = "<?xml version='1.0' encoding='UTF-8'?>\n"
+ "<FeatureTypeStyle xmlns=\"http://www.opengis.net/se\" xmlns:ogc=\"http://www.opengis.net/ogc\"\n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " xsi:schemaLocation=\"http://www.opengis.net/ogc http://schemas.opengis.net/filter/1.1.0/filter.xsd http://www.opengis.net/se http://schemas.opengis.net/se/1.1.0/FeatureStyle.xsd\"\n"
+ " version=\"1.1.0\">\n"
+ " <Name>Rivers</Name>\n"
+ " <Description>\n"
+ " <Title>Rivers</Title>\n"
+ " <Abstract>Visualizes objects as blue lines.</Abstract>\n"
+ " </Description>\n"
+ " <Rule>\n"
+ " <LineSymbolizer>\n"
+ " <Stroke>\n"
+ " <SvgParameter name=\"stroke\">#2020ff</SvgParameter>\n"
+ " <SvgParameter name=\"stroke-width\">1</SvgParameter>\n"
+ " </Stroke>\n"
+ " </LineSymbolizer>\n"
+ " </Rule>\n"
+ "</FeatureTypeStyle>";
TLcdSLDFeatureTypeStyle sldStyle = TLcdSLDFeatureTypeStyleDecoder.decodeFromString(sldAsString);
Creating an SLD-styled GXY layer
You can use TLcdSLDFeatureTypeStyle
to style your GXY layer, as illustrated below:
TLcdSLDFeatureTypeStyle sldStyle = new TLcdSLDFeatureTypeStyleDecoder()
.decodeFeatureTypeStyle("Data/Shp/Usa/rivers.sld");
//This works for both vector and raster data
ILcdGXYLayer layer = new TLcdSLDGXYLayerFactory().createGXYLayer(model, Collections.singletonList(sldStyle));
Updating the SLD style on a GXY layer
If you have an existing GXY layer, and you want to switch to SLD styling, or update the current SLD style, you can use the
static method TLcdSLDGXYLayerFactory.configureForSLDStyling
method:
if (layer instanceof TLcdGXYLayer) {
TLcdSLDGXYLayerFactory.configureForSLDStyling(sldStyle, (TLcdGXYLayer) layer);
}