Inheritance: Style, ICloneable
        private LabelStyle CalculateLabelStyle(SharpMap.Styles.LabelStyle min, SharpMap.Styles.LabelStyle max, double value)
        {
            LabelStyle style = new LabelStyle();

            style.CollisionDetection = min.CollisionDetection;
            style.Enabled            = InterpolateBool(min.Enabled, max.Enabled, value);
            float FontSize = InterpolateFloat(min.Font.Size, max.Font.Size, value);

            style.Font = new System.Drawing.Font(min.Font.FontFamily, FontSize, min.Font.Style);
            if (min.BackColor != null && max.BackColor != null)
            {
                style.BackColor = InterpolateBrush(min.BackColor, max.BackColor, value);
            }

            if (_TextColorBlend != null)
            {
                style.ForeColor = _LineColorBlend.GetColor(Convert.ToSingle(Fraction(value)));
            }
            else
            {
                style.ForeColor = InterpolateColor(min.ForeColor, max.ForeColor, value);
            }
            if (min.Halo != null && max.Halo != null)
            {
                style.Halo = InterpolatePen(min.Halo, max.Halo, value);
            }

            style.MinVisible = InterpolateDouble(min.MinVisible, max.MinVisible, value);
            style.MaxVisible = InterpolateDouble(min.MaxVisible, max.MaxVisible, value);
            style.Offset     = new System.Drawing.PointF(InterpolateFloat(min.Offset.X, max.Offset.X, value), InterpolateFloat(min.Offset.Y, max.Offset.Y, value));
            return(style);
        }
Example #2
0
        /// <summary>
        /// Delegate to create label style per feature based by style attribute.
        /// </summary>
        /// <param name="row"></param>
        /// <returns>IStyle Vector style to use for this feature</returns>
        private IStyle GetLabelStyle(FeatureDataRow row)
        {
            Style      featureStyle = (Style)row["style"];
            LabelStyle labelStyle   = new SharpMap.Styles.LabelStyle();

            if (featureStyle.fontSize == null)
            {
                return(labelStyle);
            }

            labelStyle.ForeColor = ColorTranslator.FromHtml(featureStyle.fontColor);
            labelStyle.Font      = new Font(FontFamily.GenericSansSerif, Int32.Parse(featureStyle.fontSize), FontStyle.Bold);

            labelStyle.HorizontalAlignment = SharpMap.Styles.LabelStyle.HorizontalAlignmentEnum.Center;
            labelStyle.VerticalAlignment   = SharpMap.Styles.LabelStyle.VerticalAlignmentEnum.Middle;

            labelStyle.Offset            = new PointF(0, -10);
            labelStyle.Halo              = new Pen(Color.Black, 2);
            labelStyle.VerticalAlignment = LabelStyle.VerticalAlignmentEnum.Bottom;

            labelStyle.CollisionDetection = false;
            labelStyle.IgnoreLength       = true;

            return(labelStyle);
        }
Example #3
0
 /// <summary>
 /// Event handler for the <see cref="Layer.StyleChanged"/> event
 /// </summary>
 /// <param name="sender">The sender</param>
 /// <param name="e">The event's arguments</param>
 private void HandleStyleChanged(object sender, EventArgs e)
 {
     if (_currentStyle != null)
         _currentStyle.Dispose();
     
     _currentStyle = _labelLayer.Style.Clone();
     _currentSize = _currentStyle.Font.Size;
 }
Example #4
0
        /// <summary>
        /// Creates an instance of this class
        /// </summary>
        /// <param name="layer"></param>
        /// <param name="map"></param>
        public FontSizeTheme(LabelLayer layer, Map map)
        {
            _labelLayer = layer;
            _map = map;

            _currentStyle = layer.Style.Clone();
            _currentSize = _currentStyle.Font.Size;
            _labelLayer.StyleChanged += HandleStyleChanged;
        }
Example #5
0
 /// <summary>
 /// Creates a new instance of a LabelLayer
 /// </summary>
 public LabelLayer(string layername)
 {
     _Style                      = new SharpMap.Styles.LabelStyle();
     this.LayerName              = layername;
     this.SmoothingMode          = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
     this.TextRenderingHint      = System.Drawing.Text.TextRenderingHint.AntiAlias;
     _MultipartGeometryBehaviour = MultipartGeometryBehaviourEnum.All;
     _LabelFilter                = SharpMap.Rendering.LabelCollisionDetection.SimpleCollisionDetection;
 }
Example #6
0
 /// <summary>
 /// Creates a new instance of a LabelLayer
 /// </summary>
 public LabelLayer(string layername)
 {
     _Style = new SharpMap.Styles.LabelStyle();
     this.LayerName = layername;
     this.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
     this.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
     _MultipartGeometryBehaviour = MultipartGeometryBehaviourEnum.All;
     _LabelFilter = SharpMap.Rendering.LabelCollisionDetection.SimpleCollisionDetection;
 }
Example #7
0
        public static bool AreLabelStylesEqual(LabelStyle lhs, LabelStyle rhs)
        {
            Assert.AreEqual(lhs.CollisionBuffer, rhs.CollisionBuffer, "CollisionBuffer differs");
            Assert.AreEqual(lhs.CollisionDetection, rhs.CollisionDetection, "CollisionDetection differs");
            Assert.AreEqual(lhs.Font, rhs.Font, "Font differs");
            Assert.AreEqual(lhs.ForeColor, rhs.ForeColor, "ForeColor differs");
            Assert.AreEqual(((SolidBrush)lhs.BackColor).Color, ((SolidBrush)rhs.BackColor).Color, "BackColor differs");
            SurrogatesTest.ComparePens(lhs.Halo, rhs.Halo);

            //ToDo Test more properties
            return true;
        }
Example #8
0
 private static IStyle StyleBasedOnAlignment(FeatureDataRow dr)
 {
     var style = new LabelStyle
     {
         HorizontalAlignment = (LabelStyle.HorizontalAlignmentEnum)(int) dr[2],
         VerticalAlignment = (LabelStyle.VerticalAlignmentEnum)(int) dr[3],
         Rotation = -20,
         BackColor = Brushes.Pink,
         Halo = new Pen(Brushes.LightBlue, 2)
     };
     return style;
 }
Example #9
0
        public void TestLabelStyle()
        {
            var lsS = new LabelStyle();
            lsS.CollisionBuffer = new SizeF(3, 3);
            lsS.CollisionDetection = true;
            lsS.Font = new Font(FontFamily.GenericMonospace, 14);
            lsS.ForeColor = Color.Brown;
            lsS.BackColor = new SolidBrush(Color.AntiqueWhite);
            lsS.Halo = new Pen(Color.Aquamarine, 2f);

            var lsD = SandD(lsS, GetFormatter());

            Assert.IsTrue(AreLabelStylesEqual(lsS, lsD));
        }
Example #10
0
    public static SharpMap.Map InitializeGradientMap(System.Drawing.Size size)
    {
        //Initialize a new map based on the simple map
        SharpMap.Map map = InitializeMap(size);
        //Set a gradient theme on the countries layer, based on Population density
        //First create two styles that specify min and max styles
        //In this case we will just use the default values and override the fill-colors
        //using a colorblender. If different line-widths, line- and fill-colors where used
        //in the min and max styles, these would automatically get linearly interpolated.
        SharpMap.Styles.VectorStyle min = new SharpMap.Styles.VectorStyle();
        SharpMap.Styles.VectorStyle max = new SharpMap.Styles.VectorStyle();
        //Create theme using a density from 0 (min) to 400 (max)
        IGradientThemeGdi <IVectorStyle> popdens = new GradientThemeIVectorStyle("PopDens", 0, 400, min, max);

        //We can make more advanced coloring using the ColorBlend'er.
        //Setting the FillColorBlend will override any fill-style in the min and max fills.
        //In this case we just use the predefined Rainbow colorscale
        popdens.FillColorBlend = SharpMap.Rendering.Thematics.ColorBlend.Rainbow5;
        (map.Layers[0] as SharpMap.Layers.VectorLayer).Theme = popdens;

        //Lets scale the labels so that big countries have larger texts as well
        SharpMap.Styles.LabelStyle lblMin = new SharpMap.Styles.LabelStyle();
        SharpMap.Styles.LabelStyle lblMax = new SharpMap.Styles.LabelStyle();
        lblMin.ForeColor = Color.Black;
        lblMin.Font      = new Font(FontFamily.GenericSerif, 6);
        lblMax.ForeColor = Color.Blue;
        lblMax.BackColor = new SolidBrush(Color.FromArgb(128, 255, 255, 255));
        lblMin.BackColor = lblMax.BackColor;
        lblMax.Font      = new Font(FontFamily.GenericSerif, 9);
        (map.Layers[3] as ILabelLayer).Theme = new GradientThemeILabelStyle("PopDens", 0, 400, lblMin, lblMax);

        //Lets scale city icons based on city population
        //cities below 1.000.000 gets the smallest symbol, and cities with more than 5.000.000 the largest symbol
        SharpMap.Styles.VectorStyle citymin = new SharpMap.Styles.VectorStyle();
        SharpMap.Styles.VectorStyle citymax = new SharpMap.Styles.VectorStyle();
        citymin.Symbol      = new Bitmap(HttpContext.Current.Server.MapPath(@"~\App_data\icon.png"));
        citymin.SymbolScale = 0.5f;
        citymax.Symbol      = new Bitmap(HttpContext.Current.Server.MapPath(@"~\App_data\icon.png"));
        citymax.SymbolScale = 1f;
        (map.Layers[2] as SharpMap.Layers.VectorLayer).Theme = new GradientThemeIVectorStyle("Population", 1000000, 5000000, citymin, citymax);

        //Turn off the river layer
        map.Layers[1].Enabled = false;
        return(map);
    }
Example #11
0
 /// <summary>
 /// Creates a new instance of a LabelLayer
 /// </summary>
 public LabelLayer(string layername)
 {
     style                      = new SharpMap.Styles.LabelStyle();
     this.Name                  = layername;
     this.SmoothingMode         = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
     this.TextRenderingHint     = System.Drawing.Text.TextRenderingHint.AntiAlias;
     multipartGeometryBehaviour = MultipartGeometryBehaviourEnum.All;
     this.ShowInTreeView        = false;
     this.ShowInLegend          = false;
     this.Visible               = false;
     this.LabelFilter           = LabelCollisionDetection.ThoroughCollisionDetection;
     this.Style                 = new LabelStyle
     {
         Font = new Font("Arial", 12),
         Halo = new Pen(Brushes.White, 1f),
         CollisionDetection = true
     };
 }
Example #12
0
		/// <summary>
		/// Creates a new instance of a LabelLayer
		/// </summary>
		public LabelLayer(string layername)
		{
			style = new SharpMap.Styles.LabelStyle();
			this.Name = layername;
			this.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
			this.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
			multipartGeometryBehaviour = MultipartGeometryBehaviourEnum.All;
            this.ShowInTreeView = false;
            this.ShowInLegend = false;
		    this.Visible = false;
            this.LabelFilter = LabelCollisionDetection.ThoroughCollisionDetection;
		    this.Style = new LabelStyle
		    {
		        Font = new Font("Arial", 12),
		        Halo = new Pen(Brushes.White, 1f),
                CollisionDetection = true
            };
		}
Example #13
0
        /// <summary>
        /// Get label style
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        private IStyle GetLabelStyle(FeatureDataRow row)
        {
            Style      featureStyle = (Style)row["style"];
            LabelStyle labelStyle   = new SharpMap.Styles.LabelStyle();

            if (featureStyle.fontSize == null)
            {
                return(labelStyle);
            }

            labelStyle.ForeColor          = ColorTranslator.FromHtml(featureStyle.fontColor);
            labelStyle.Font               = new Font(FontFamily.GenericSansSerif, Int32.Parse(featureStyle.fontSize), FontStyle.Bold);
            labelStyle.Halo               = new Pen(Color.Black, 2);
            labelStyle.IsTextOnPath       = true;
            labelStyle.CollisionDetection = false;
            labelStyle.IgnoreLength       = false;

            return(labelStyle);
        }
Example #14
0
        /// <summary>
        /// Renders the layer
        /// </summary>
        /// <param name="g">Graphics object reference</param>
        /// <param name="map">Map which is rendered</param>
        public override void OnRender(System.Drawing.Graphics g, Map map)
        {
            if (Style.Enabled && Style.MaxVisible >= map.Zoom && Style.MinVisible < map.Zoom)
            {
                if (DataSource == null)
                {
                    throw (new ApplicationException("DataSource property not set on layer '" + Name + "'"));
                }
                g.TextRenderingHint = this.TextRenderingHint;
                g.SmoothingMode     = this.SmoothingMode;

                IEnvelope envelope = map.Envelope;                 //View to render
                if (CoordinateTransformation != null)
                {
                    envelope = CoordinateSystems.Transformations.GeometryTransform.TransformBox(envelope, this.CoordinateTransformation.MathTransform.Inverse());
                }

                IList features = DataSource.GetFeatures(envelope);

                if (features.Count == 0)
                {
                    return;
                }

                //Initialize label collection
                var labels = new List <Rendering.Label>();

                //List<System.Drawing.Rectangle> LabelBoxes; //Used for collision detection
                //Render labels
                for (int i = 0; i < features.Count; i++)
                {
                    IFeature feature = (IFeature)features[i];
                    if (this.CoordinateTransformation != null)
                    {
                        ((IFeature)features[i]).Geometry = SharpMap.CoordinateSystems.Transformations.GeometryTransform.TransformGeometry(((IFeature)features[i]).Geometry, this.CoordinateTransformation.MathTransform);
                    }

                    SharpMap.Styles.LabelStyle style = null;
                    if (this.Theme != null)                     //If thematics is enabled, lets override the style
                    {
                        style = this.Theme.GetStyle(feature) as SharpMap.Styles.LabelStyle;
                    }
                    else
                    {
                        style = this.Style;
                    }

                    float rotation = 0;
                    if (!String.IsNullOrEmpty(this.RotationColumn))
                    {
                        rotation = FeatureAttributeAccessorHelper.GetAttributeValue <float>(feature, RotationColumn, 0f);
                    }

                    string text = GetText(feature);

                    if (text != null && text != String.Empty)
                    {
                        if (feature.Geometry is IGeometryCollection)
                        {
                            if (this.MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.All)
                            {
                                foreach (IGeometry geom in (feature.Geometry as IGeometryCollection))
                                {
                                    SharpMap.Rendering.Label lbl = CreateLabel(geom, text, rotation, style, map, g);
                                    if (lbl != null)
                                    {
                                        labels.Add(lbl);
                                    }
                                }
                            }
                            else if (this.MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.CommonCenter)
                            {
                                SharpMap.Rendering.Label lbl = CreateLabel(feature.Geometry, text, rotation, style, map, g);
                                if (lbl != null)
                                {
                                    labels.Add(lbl);
                                }
                            }
                            else if (this.MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.First)
                            {
                                if ((feature.Geometry as IGeometryCollection).Geometries.Length > 0)
                                {
                                    SharpMap.Rendering.Label lbl = CreateLabel((feature.Geometry as IGeometryCollection).Geometries[0], text, rotation, style, map, g);
                                    if (lbl != null)
                                    {
                                        labels.Add(lbl);
                                    }
                                }
                            }
                            else if (this.MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.Largest)
                            {
                                IGeometryCollection coll = (feature.Geometry as IGeometryCollection);
                                if (coll.NumGeometries > 0)
                                {
                                    double largestVal   = 0;
                                    int    idxOfLargest = 0;
                                    for (int j = 0; j < coll.NumGeometries; j++)
                                    {
                                        IGeometry geom = coll.Geometries[j];
                                        if (geom is ILineString && ((ILineString)geom).Length > largestVal)
                                        {
                                            largestVal   = ((ILineString)geom).Length;
                                            idxOfLargest = j;
                                        }
                                        if (geom is IMultiLineString && ((IMultiLineString)geom).Length > largestVal)
                                        {
                                            largestVal   = ((ILineString)geom).Length;
                                            idxOfLargest = j;
                                        }
                                        if (geom is IPolygon && ((IPolygon)geom).Area > largestVal)
                                        {
                                            largestVal   = ((IPolygon)geom).Area;
                                            idxOfLargest = j;
                                        }
                                        if (geom is IMultiPolygon && ((IMultiPolygon)geom).Area > largestVal)
                                        {
                                            largestVal   = ((IMultiPolygon)geom).Area;
                                            idxOfLargest = j;
                                        }
                                    }

                                    SharpMap.Rendering.Label lbl = CreateLabel(coll.Geometries[idxOfLargest], text, rotation, style, map, g);
                                    if (lbl != null)
                                    {
                                        labels.Add(lbl);
                                    }
                                }
                            }
                        }
                        else
                        {
                            SharpMap.Rendering.Label lbl = CreateLabel(feature.Geometry, text, rotation, style, map, g);
                            if (lbl != null)
                            {
                                labels.Add(lbl);
                            }
                        }
                    }
                }
                if (labels.Count > 0)                 //We have labels to render...
                {
                    if (this.Style.CollisionDetection && this.labelFilter != null)
                    {
                        this.labelFilter(labels);
                    }
                    for (int i = 0; i < labels.Count; i++)
                    {
                        SharpMap.Rendering.VectorRenderingHelper.DrawLabel(g, labels[i].LabelPoint, labels[i].Style.Offset, labels[i].Style.Font, labels[i].Style.ForeColor, labels[i].Style.BackColor, Style.Halo, labels[i].Rotation, labels[i].Text, map);
                    }
                }
                labels = null;
            }
        }
Example #15
0
	public static SharpMap.Map InitializeGradientMap(System.Drawing.Size size)
	{
		//Initialize a new map based on the simple map
		SharpMap.Map map = InitializeMap(size);
		//Set a gradient theme on the countries layer, based on Population density
		//First create two styles that specify min and max styles
		//In this case we will just use the default values and override the fill-colors
		//using a colorblender. If different line-widths, line- and fill-colors where used
		//in the min and max styles, these would automatically get linearly interpolated.
		SharpMap.Styles.VectorStyle min = new SharpMap.Styles.VectorStyle();
		SharpMap.Styles.VectorStyle max = new SharpMap.Styles.VectorStyle();
		//Create theme using a density from 0 (min) to 400 (max)
		SharpMap.Rendering.Thematics.GradientTheme popdens = new SharpMap.Rendering.Thematics.GradientTheme("PopDens", 0, 400, min, max);
		//We can make more advanced coloring using the ColorBlend'er.
		//Setting the FillColorBlend will override any fill-style in the min and max fills.
		//In this case we just use the predefined Rainbow colorscale
		popdens.FillColorBlend = SharpMap.Rendering.Thematics.ColorBlend.Rainbow5;
		(map.Layers[0] as SharpMap.Layers.VectorLayer).Theme = popdens;

		//Lets scale the labels so that big countries have larger texts as well
		SharpMap.Styles.LabelStyle lblMin = new SharpMap.Styles.LabelStyle();
		SharpMap.Styles.LabelStyle lblMax = new SharpMap.Styles.LabelStyle();
		lblMin.ForeColor = Color.Black;
		lblMin.Font = new Font(FontFamily.GenericSerif, 6);
		lblMax.ForeColor = Color.Blue;
		lblMax.BackColor = new SolidBrush(Color.FromArgb(128, 255, 255, 255));
		lblMin.BackColor = lblMax.BackColor;
		lblMax.Font = new Font(FontFamily.GenericSerif, 9);
		(map.Layers[3] as SharpMap.Layers.LabelLayer).Theme = new SharpMap.Rendering.Thematics.GradientTheme("PopDens", 0, 400, lblMin, lblMax);		
		
		//Lets scale city icons based on city population
		//cities below 1.000.000 gets the smallest symbol, and cities with more than 5.000.000 the largest symbol
		SharpMap.Styles.VectorStyle citymin = new SharpMap.Styles.VectorStyle();
		SharpMap.Styles.VectorStyle citymax = new SharpMap.Styles.VectorStyle();
		citymin.Symbol = new Bitmap(HttpContext.Current.Server.MapPath(@"~\App_data\icon.png"));
		citymin.SymbolScale = 0.5f;
		citymax.Symbol = new Bitmap(HttpContext.Current.Server.MapPath(@"~\App_data\icon.png"));
		citymax.SymbolScale = 1f;
		(map.Layers[2] as SharpMap.Layers.VectorLayer).Theme = new SharpMap.Rendering.Thematics.GradientTheme("Population", 1000000, 5000000, citymin, citymax);
	
		//Turn off the river layer
		map.Layers[1].Enabled = false;
		return map;
	}
Example #16
0
 /// <summary>
 /// Creates a new instance of a LabelLayer
 /// </summary>
 public LabelLayer(string LayerName)
     : base(LayerName)
 {
     _Style = new LabelStyle();
     _MultipartGeometryBehaviour = MultipartGeometryBehaviourEnum.All;
     _LabelFilter = LabelCollisionDetection.SimpleCollisionDetection;
 }
Example #17
0
        public override void Render(System.Drawing.Graphics g, Map map)
        {
            if (this.Style.Enabled && this.Style.MaxVisible >= map.Zoom && this.Style.MinVisible < map.Zoom)
            {
                if (this.DataSource == null)
                {
                    throw (new ApplicationException("DataSource property not set on layer '" + this.LayerName + "'"));
                }
                g.TextRenderingHint = this.TextRenderingHint;
                g.SmoothingMode     = this.SmoothingMode;

                SharpMap.Geometries.BoundingBox envelope = map.Envelope; //View to render
                if (this.CoordinateTransformation != null)
                {
                    envelope = SharpMap.CoordinateSystems.Transformations.GeometryTransform.TransformBox(envelope, this.CoordinateTransformation.MathTransform.Inverse());
                }

                SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet();
                this.DataSource.Open();
                this.DataSource.ExecuteIntersectionQuery(envelope, ds);
                this.DataSource.Close();
                if (ds.Tables.Count == 0)
                {
                    base.Render(g, map);
                    return;
                }
                SharpMap.Data.FeatureDataTable features = (SharpMap.Data.FeatureDataTable)ds.Tables[0];

                //Initialize label collection
                List <Rendering.Label> labels = new List <SharpMap.Rendering.Label>();

                //List<System.Drawing.Rectangle> LabelBoxes; //Used for collision detection
                //Render labels
                for (int i = 0; i < features.Count; i++)
                {
                    SharpMap.Data.FeatureDataRow feature = features[i];
                    if (this.CoordinateTransformation != null)
                    {
                        features[i].Geometry = SharpMap.CoordinateSystems.Transformations.GeometryTransform.TransformGeometry(features[i].Geometry, this.CoordinateTransformation.MathTransform);
                    }

                    SharpMap.Styles.LabelStyle style = null;
                    if (this.Theme != null) //If thematics is enabled, lets override the style
                    {
                        style = this.Theme.GetStyle(feature) as SharpMap.Styles.LabelStyle;
                    }
                    else
                    {
                        style = this.Style;
                    }

                    float rotation = 0;
                    if (!String.IsNullOrEmpty(this.RotationColumn))
                    {
                        float.TryParse(feature[this.RotationColumn].ToString(), System.Globalization.NumberStyles.Any, SharpMap.Map.numberFormat_EnUS, out rotation);
                    }

                    string text;
                    if (_getLabelMethod != null)
                    {
                        text = _getLabelMethod(feature);
                    }
                    else
                    {
                        text = feature[this.LabelColumn].ToString();
                    }

                    if (text != null && text != String.Empty)
                    {
                        if (feature.Geometry is SharpMap.Geometries.GeometryCollection)
                        {
                            if (this.MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.All)
                            {
                                foreach (SharpMap.Geometries.Geometry geom in (feature.Geometry as Geometries.GeometryCollection))
                                {
                                    SharpMap.Rendering.Label lbl = CreateLabel(geom, text, rotation, style, map, g);
                                    if (lbl != null)
                                    {
                                        labels.Add(lbl);
                                    }
                                }
                            }
                            else if (this.MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.CommonCenter)
                            {
                                SharpMap.Rendering.Label lbl = CreateLabel(feature.Geometry, text, rotation, style, map, g);
                                if (lbl != null)
                                {
                                    labels.Add(lbl);
                                }
                            }
                            else if (this.MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.First)
                            {
                                if ((feature.Geometry as Geometries.GeometryCollection).Collection.Count > 0)
                                {
                                    SharpMap.Rendering.Label lbl = CreateLabel((feature.Geometry as Geometries.GeometryCollection).Collection[0], text, rotation, style, map, g);
                                    if (lbl != null)
                                    {
                                        labels.Add(lbl);
                                    }
                                }
                            }
                            else if (this.MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.Largest)
                            {
                                Geometries.GeometryCollection coll = (feature.Geometry as Geometries.GeometryCollection);
                                if (coll.NumGeometries > 0)
                                {
                                    double largestVal   = 0;
                                    int    idxOfLargest = 0;
                                    for (int j = 0; j < coll.NumGeometries; j++)
                                    {
                                        SharpMap.Geometries.Geometry geom = coll.Geometry(j);
                                        if (geom is Geometries.LineString && ((Geometries.LineString)geom).Length > largestVal)
                                        {
                                            largestVal   = ((Geometries.LineString)geom).Length;
                                            idxOfLargest = j;
                                        }
                                        if (geom is Geometries.MultiLineString && ((Geometries.MultiLineString)geom).Length > largestVal)
                                        {
                                            largestVal   = ((Geometries.LineString)geom).Length;
                                            idxOfLargest = j;
                                        }
                                        if (geom is Geometries.Polygon && ((Geometries.Polygon)geom).Area > largestVal)
                                        {
                                            largestVal   = ((Geometries.Polygon)geom).Area;
                                            idxOfLargest = j;
                                        }
                                        if (geom is Geometries.MultiPolygon && ((Geometries.MultiPolygon)geom).Area > largestVal)
                                        {
                                            largestVal   = ((Geometries.MultiPolygon)geom).Area;
                                            idxOfLargest = j;
                                        }
                                    }

                                    SharpMap.Rendering.Label lbl = CreateLabel(coll.Geometry(idxOfLargest), text, rotation, style, map, g);
                                    if (lbl != null)
                                    {
                                        labels.Add(lbl);
                                    }
                                }
                            }
                        }
                        else
                        {
                            SharpMap.Rendering.Label lbl = CreateLabel(feature.Geometry, text, rotation, style, map, g);
                            if (lbl != null)
                            {
                                labels.Add(lbl);
                            }
                        }
                    }
                }
                if (labels.Count > 0) //We have labels to render...
                {
                    if (this.Style.CollisionDetection && this._LabelFilter != null)
                    {
                        this._LabelFilter(labels);
                    }
                    for (int i = 0; i < labels.Count; i++)
                    {
                        SharpMap.Rendering.VectorRenderer.DrawLabel(g, labels[i].LabelPoint, labels[i].Style.Offset, labels[i].Style.Font, labels[i].Style.ForeColor, labels[i].Style.BackColor, Style.Halo, labels[i].Rotation, labels[i].Text, map);
                    }
                }
                labels = null;
            }
            base.Render(g, map);
        }
Example #18
0
 private BaseLabel CreateLabel(FeatureDataRow fdr, Geometry feature, string text, float rotation, LabelStyle style, Map map, Graphics g)
 {
     return CreateLabel(fdr, feature, text, rotation, Priority, style, map, g, _getLocationMethod);
 }
Example #19
0
 private IStyle GetLabelStyle(ICssStyleDeclaration csd)
 { //   LabelStyle object rebuild. Deserializes:
     //   font-family        Font.Family
     //   font-size          Font.Size
     //   font-color         ForeColor
     //   background-color   BackColor
     //   border-color       Halo.Color
     //   border-width       Halo.Width
     //   padding-horizontal Offset.X
     //   padding-vertical   Offset.Y
     //   text-align         HorizontalAlignment
     //   vertical-align     VerticalAlignment
     LabelStyle lStyle =new LabelStyle();
     string fontFamily = lStyle.Font.FontFamily.Name;
     float fontSize = lStyle.Font.Size;
     if (csd.GetPropertyValue("font-family") != string.Empty)
         fontFamily = csd.GetPropertyValue("font-family");
     if (csd.GetPropertyValue("font-size") != string.Empty)
         fontSize = float.Parse(csd.GetPropertyValue("font-size"));
     lStyle.Font = new Font(fontFamily, fontSize);
     if (csd.GetPropertyValue("font-color") != string.Empty)
         lStyle.ForeColor = GetColorFromCss(csd, "font-color");
     if (csd.GetPropertyValue("background-color") != string.Empty)
         lStyle.BackColor = new SolidBrush(GetColorFromCss(csd, "back-color"));
     Color haloColor = lStyle.Halo.Color;
     float haloWidth = lStyle.Halo.Width;
     if (csd.GetPropertyValue("border-color") != string.Empty)
         haloColor = GetColorFromCss(csd, "border-color");
     if (csd.GetPropertyValue("border-width") != string.Empty)
         haloWidth = float.Parse(csd.GetPropertyValue("border-width"));
     lStyle.Halo = new Pen(haloColor, haloWidth);
     float offsetX = lStyle.Offset.X;
     float offsetY = lStyle.Offset.Y;
     if (csd.GetPropertyValue("padding-horizontal") != null)
         offsetX = float.Parse(csd.GetPropertyValue("padding-horizontal"));
     if (csd.GetPropertyValue("padding-vertical") != null)
         offsetY = float.Parse(csd.GetPropertyValue("padding-vertical"));
     lStyle.Offset = new PointF(offsetX, offsetY);
     if (csd.GetPropertyValue("text-align") != null)
         lStyle.HorizontalAlignment = (LabelStyle.HorizontalAlignmentEnum)Enum.Parse(typeof(LabelStyle.HorizontalAlignmentEnum),
                                                                                     csd.GetPropertyValue("text-align"));
     if (csd.GetPropertyValue("vertical-align") != null)
         lStyle.VerticalAlignment = (LabelStyle.VerticalAlignmentEnum)Enum.Parse(typeof(LabelStyle.VerticalAlignmentEnum),
                                                                                 csd.GetPropertyValue("vertical-align"));
     return lStyle;
 }
Example #20
0
        private static BaseLabel CreateLabel(Geometry feature, string text, float rotation, int priority, LabelStyle style, Map map,
                                  Graphics g)
        {
            BaseLabel lbl = null;

            SizeF size = VectorRenderer.SizeOfString(g, text, style.Font);

            if (feature is ILineal)
            {
                var line = feature as LineString;
                if (line != null)
                {
                    if (size.Width < 0.95 * line.Length / map.PixelWidth || !style.IgnoreLength)
                    {
                        var positiveLineString = PositiveLineString(line, false);
                        var lineStringPath = LineStringToPath(positiveLineString, map /*, false*/);
                        var rect = lineStringPath.GetBounds();

                        if (style.CollisionDetection && !style.CollisionBuffer.IsEmpty)
                        {
                            var cbx = style.CollisionBuffer.Width;
                            var cby = style.CollisionBuffer.Height;
                            rect.Inflate(2*cbx, 2*cby);
                            rect.Offset(-cbx, -cby);
                        }
                        var labelBox = new LabelBox(rect);

                        lbl = new PathLabel(text, lineStringPath, 0, priority, labelBox, style);
                    }
                }
                return lbl;
            }
            
            PointF position = Transform.WorldtoMap(feature.GetBoundingBox().GetCentroid(), map);

            position.X = position.X - size.Width*(short) style.HorizontalAlignment*0.5f;
            position.Y = position.Y - size.Height*(short) (2-(int)style.VerticalAlignment)*0.5f;
            if (position.X - size.Width > map.Size.Width || position.X + size.Width < 0 ||
                position.Y - size.Height > map.Size.Height || position.Y + size.Height < 0)
                return null;

            if (!style.CollisionDetection)
                lbl = new Label(text, position, rotation, priority, null, style);
            else
            {
                //Collision detection is enabled so we need to measure the size of the string
                lbl = new Label(text, position, rotation, priority,
                                new LabelBox(position.X - size.Width*0.5f - style.CollisionBuffer.Width,
                                             position.Y + size.Height*0.5f + style.CollisionBuffer.Height,
                                             size.Width + 2f*style.CollisionBuffer.Width,
                                             size.Height + style.CollisionBuffer.Height*2f), style);
            }

            /*
            if (feature is LineString)
            {
                var line = feature as LineString;

                //Only label feature if it is long enough, or it is definately wanted                
                if (line.Length / map.PixelSize > size.Width || style.IgnoreLength)
                {
                    CalculateLabelOnLinestring(line, ref lbl, map);
                }
                else
                    return null;
            }
            */
            return lbl;
        }
Example #21
0
		private LabelStyle CalculateLabelStyle(SharpMap.Styles.LabelStyle min, SharpMap.Styles.LabelStyle max, double value)
		{
			LabelStyle style = new LabelStyle();
			style.CollisionDetection = min.CollisionDetection;
			style.Enabled = InterpolateBool(min.Enabled, max.Enabled,value);
			float FontSize = InterpolateFloat(min.Font.Size,max.Font.Size,value);
			style.Font = new System.Drawing.Font(min.Font.FontFamily,FontSize,min.Font.Style);
			if (min.BackColor != null && max.BackColor != null)
				style.BackColor = InterpolateBrush(min.BackColor, max.BackColor, value);

			if (_TextColorBlend != null)
				style.ForeColor = _LineColorBlend.GetColor(Convert.ToSingle(Fraction(value)));
			else 
				style.ForeColor = InterpolateColor(min.ForeColor, max.ForeColor, value);
			if (min.Halo != null && max.Halo != null)
				style.Halo = InterpolatePen(min.Halo,max.Halo, value);

			style.MinVisible = InterpolateDouble(min.MinVisible,max.MinVisible,value);
			style.MaxVisible = InterpolateDouble(min.MaxVisible, max.MaxVisible, value);
			style.Offset = new System.Drawing.PointF(InterpolateFloat(min.Offset.X, max.Offset.X, value), InterpolateFloat(min.Offset.Y, max.Offset.Y, value));
			return style;
		}
Example #22
0
	    protected LabelStyle(LabelStyle another) : base(another)
	    {
	        _Font = (Font) another.Font.Clone();
            _Offset = another.Offset;
            _CollisionDetection = another.CollisionDetection;
            _CollisionBuffer = another.CollisionBuffer;
            _ForeColor = another.ForeColor;
            _HorisontalAlignment = another.HorizontalAlignment;
            _VerticalAlignment = another.VerticalAlignment;
	    }
        private IStyle calculateLabelStyle(IStyle min, IStyle max, double value)
        {
            if (!(min is LabelStyle && max is LabelStyle))
            {
                throw new ArgumentException(
                    "Both min style and max style must be label styles to compute a gradient label style");
            }

            LabelStyle style = new LabelStyle();
            LabelStyle labelMin = min as LabelStyle;
            LabelStyle labelMax = max as LabelStyle;

            style.CollisionDetection = labelMin.CollisionDetection;
            style.Enabled = interpolateBool(min.Enabled, max.Enabled, value);

            double fontSize = interpolateDouble(labelMin.Font.Size.Width, labelMax.Font.Size.Width, value);
            style.Font = new StyleFont(labelMin.Font.FontFamily, new Size2D(fontSize, fontSize), labelMin.Font.Style);

            if (labelMin.BackColor != null && labelMax.BackColor != null)
            {
                style.BackColor = interpolateBrush(labelMin.BackColor, labelMax.BackColor, value);
            }

            if (_textColorBlend != null)
            {
                style.ForeColor = _lineColorBlend.GetColor(Convert.ToSingle(fraction(value)));
            }
            else
            {
                style.ForeColor = StyleColor.Interpolate(labelMin.ForeColor, labelMax.ForeColor, value);
            }

            if (labelMin.Halo != null && labelMax.Halo != null)
            {
                style.Halo = interpolatePen(labelMin.Halo, labelMax.Halo, value);
            }

            style.MinVisible = interpolateDouble(labelMin.MinVisible, labelMax.MinVisible, value);
            style.MaxVisible = interpolateDouble(labelMin.MaxVisible, labelMax.MaxVisible, value);
            style.Offset = new Point2D(interpolateDouble(labelMin.Offset.X, labelMax.Offset.X, value),
                                       interpolateDouble(labelMin.Offset.Y, labelMax.Offset.Y, value));

            return style;
        }
        private LabelStyle CalculateLabelStyle(SharpMap.Styles.LabelStyle min, SharpMap.Styles.LabelStyle max, double value)
        {
            LabelStyle style = new LabelStyle();
            style.CollisionDetection = min.CollisionDetection;
            style.Enabled = InterpolateBool(min.Enabled, max.Enabled, value);

            double FontSize = InterpolateDouble(min.Font.Size, max.Font.Size, value);
            style.Font = new Font() { FontFamily = min.Font.FontFamily, Size = min.Font.Size };

            if (min.BackColor != null && max.BackColor != null)
                style.BackColor = InterpolateBrush(min.BackColor, max.BackColor, value);

            if (_TextColorBlend != null)
                style.ForeColor = _LineColorBlend.GetColor(Convert.ToSingle(Fraction(value)));
            else
                style.ForeColor = InterpolateColor(min.ForeColor, max.ForeColor, value);
            if (min.Halo != null && max.Halo != null)
                style.Halo = InterpolatePen(min.Halo, max.Halo, value);

            style.MinVisible = InterpolateDouble(min.MinVisible, max.MinVisible, value);
            style.MaxVisible = InterpolateDouble(min.MaxVisible, max.MaxVisible, value);
#if !CFBuild //No PointF in CF, use Point instead.
            var X = InterpolateFloat(min.Offset.X, max.Offset.X, value);
            var Y = InterpolateFloat(min.Offset.Y, max.Offset.Y, value);
            style.Offset = new Offset() { X = X, Y = Y };
#else
            style.Offset = new Point((int)InterpolateFloat(min.Offset.X, max.Offset.X, value), (int)InterpolateFloat(min.Offset.Y, max.Offset.Y, value));
#endif

            return style;
        }
Example #25
0
        /// <summary>
        /// Method to update the style according to the new size
        /// </summary>
        /// <param name="labelStyle">The label style</param>
        /// <param name="newSize">A new size</param>
        /// <returns>The updated label style</returns>
        protected virtual LabelStyle UpdateStyle(LabelStyle labelStyle, float newSize)
        {
            if (MinFontSize.HasValue && newSize < MinFontSize)
            {
                labelStyle.Enabled = false;
                return labelStyle;
            }
            
            // Make sure label style is enabled
            labelStyle.Enabled = true;

            // Is there a significant change in the font size?
            if (Math.Round(newSize) != Math.Round(labelStyle.Font.Size))
            {
                // Store the old font
                var oldFont = labelStyle.Font;

                // Build a new font
                labelStyle.Font = new Font(oldFont.FontFamily, newSize, oldFont.Style, GraphicsUnit.Pixel);

                // Dispose the old font
                if (oldFont != null) oldFont.Dispose();
            }
            return labelStyle;
        }
Example #26
0
        private SharpMap.Rendering.Label CreateLabel(IGeometry feature, string text, float rotation, SharpMap.Styles.LabelStyle style, Map map, System.Drawing.Graphics g)
        {
            System.Drawing.SizeF size = g.MeasureString(text, style.Font);

            System.Drawing.PointF position = map.WorldToImage(feature.EnvelopeInternal.Centre);
            position.X = position.X - size.Width * (short)style.HorizontalAlignment * 0.5f;
            position.Y = position.Y - size.Height * (short)style.VerticalAlignment * 0.5f;
            if (position.X - size.Width > map.Size.Width || position.X + size.Width < 0 ||
                position.Y - size.Height > map.Size.Height || position.Y + size.Height < 0)
            {
                return(null);
            }
            else
            {
                SharpMap.Rendering.Label lbl;

                if (!style.CollisionDetection)
                {
                    lbl = new SharpMap.Rendering.Label(text, position, rotation, this.Priority, null, style);
                }
                else
                {
                    //Collision detection is enabled so we need to measure the size of the string
                    lbl = new SharpMap.Rendering.Label(text, position, rotation, this.Priority,
                                                       new SharpMap.Rendering.LabelBox(position.X - size.Width * 0.5f - style.CollisionBuffer.Width, position.Y + size.Height * 0.5f + style.CollisionBuffer.Height,
                                                                                       size.Width + 2f * style.CollisionBuffer.Width, size.Height + style.CollisionBuffer.Height * 2f), style);
                }
                if (feature.GetType() == typeof(ILineString))
                {
                    ILineString line = feature as ILineString;
                    if (line.Length / map.PixelSize > size.Width)                     //Only label feature if it is long enough
                    {
                        CalculateLabelOnLinestring(line, ref lbl, map);
                    }
                    else
                    {
                        return(null);
                    }
                }

                return(lbl);
            }
        }
Example #27
0
        /// <summary>
        /// Function to compute a new <see cref="LabelStyle">style</see> for the given <paramref name="value"/>
        /// </summary>
        /// <param name="min">The minimum <see cref="LabelStyle">style</see></param>
        /// <param name="max">The maximum <see cref="LabelStyle">style</see></param>
        /// <param name="value">The value</param>
        /// <returns>A <see cref="LabelStyle">style</see></returns>
        protected LabelStyle CalculateLabelStyle(LabelStyle min, LabelStyle max, double value)
        {
            LabelStyle style = new LabelStyle();
            style.CollisionDetection = min.CollisionDetection;
            style.Enabled = InterpolateBool(min.Enabled, max.Enabled, value);
            float fontSize = InterpolateFloat(min.Font.Size, max.Font.Size, value);
            style.Font = new Font(min.Font.FontFamily, fontSize, min.Font.Style);
            if (min.BackColor != null && max.BackColor != null)
                style.BackColor = InterpolateBrush(min.BackColor, max.BackColor, value);

            if (_textColorBlend != null)
                style.ForeColor = _lineColorBlend.GetColor(Convert.ToSingle(Fraction(value)));
            else
                style.ForeColor = InterpolateColor(min.ForeColor, max.ForeColor, value);
            if (min.Halo != null && max.Halo != null)
                style.Halo = InterpolatePen(min.Halo, max.Halo, value);

            style.VisibilityUnits = min.VisibilityUnits;
            style.MinVisible = InterpolateDouble(min.MinVisible, max.MinVisible, value);
            style.MaxVisible = InterpolateDouble(min.MaxVisible, max.MaxVisible, value);
            style.Offset = new PointF(InterpolateFloat(min.Offset.X, max.Offset.X, value),
                                      InterpolateFloat(min.Offset.Y, max.Offset.Y, value));
            return style;
        }
Example #28
0
        private IStyle GetLabelStyle(FeatureDataRow row)
        {
            Style featureStyle = (Style)row["style"];
            LabelStyle labelStyle = new SharpMap.Styles.LabelStyle();

            if (featureStyle.fontSize == null)
            {
                return labelStyle;
            }

            labelStyle.ForeColor = ColorTranslator.FromHtml(featureStyle.fontColor);
            labelStyle.Font = new Font(FontFamily.GenericSansSerif, Int32.Parse(featureStyle.fontSize), FontStyle.Bold);
            labelStyle.Halo = new Pen(Color.Black, 2);
            labelStyle.IsTextOnPath = true;
            labelStyle.CollisionDetection = false;
            labelStyle.IgnoreLength = false;

            return labelStyle;
        }
Example #29
0
        private static BaseLabel CreateLabel(FeatureDataRow fdr, IGeometry feature, string text, float rotation, int priority, LabelStyle style, Map map, Graphics g, GetLocationMethod _getLocationMethod)
        {
            if (feature == null) return null;

            BaseLabel lbl = null;

            SizeF size = VectorRenderer.SizeOfString(g, text, style.Font);

            if (feature is ILineal)
            {
                var line = feature as ILineString;
                if (line != null)
                {
                    if (style.IsTextOnPath == false)
                    {
                        if (size.Width < 0.95 * line.Length / map.PixelWidth || style.IgnoreLength)
                        {
                            var positiveLineString = PositiveLineString(line, false);
                            var lineStringPath = LineStringToPath(positiveLineString, map /*, false*/);
                            var rect = lineStringPath.GetBounds();

                            if (style.CollisionDetection && !style.CollisionBuffer.IsEmpty)
                            {
                                var cbx = style.CollisionBuffer.Width;
                                var cby = style.CollisionBuffer.Height;
                                rect.Inflate(2 * cbx, 2 * cby);
                                rect.Offset(-cbx, -cby);
                            }
                            var labelBox = new LabelBox(rect);

                            lbl = new PathLabel(text, lineStringPath, 0, priority, labelBox, style);
                        }
                    }
                    else
                    {
                        //get centriod
                        System.Drawing.PointF position2 = map.WorldToImage(feature.EnvelopeInternal.Centre);
                        lbl = new Label(text, position2, rotation, priority, style);
                        if (size.Width < 0.95 * line.Length / map.PixelWidth || !style.IgnoreLength)
                        {
                            CalculateLabelAroundOnLineString(line, ref lbl, map, g, size);
                        }
                    }
                }
                return lbl;
            }

            var worldPosition = _getLocationMethod == null
                ? feature.EnvelopeInternal.Centre
                : _getLocationMethod(fdr);

            if (worldPosition == null) return null;

            var position = Transform.WorldtoMap(worldPosition, map);

            var location = new PointF(
                position.X - size.Width*(short) style.HorizontalAlignment*0.5f,
                position.Y - size.Height*(short) (2 - (int) style.VerticalAlignment)*0.5f);

            if (location.X - size.Width > map.Size.Width || location.X + size.Width < 0 ||
                location.Y - size.Height > map.Size.Height || location.Y + size.Height < 0)
                return null;

            if (!style.CollisionDetection)
                lbl = new Label(text, location, rotation, priority, null, style)
                    {LabelPoint = position};
            else
            {
                //Collision detection is enabled so we need to measure the size of the string
                lbl = new Label(text, location, rotation, priority,
                                new LabelBox(location.X - size.Width*0.5f - style.CollisionBuffer.Width,
                                             location.Y + size.Height*0.5f + style.CollisionBuffer.Height,
                                             size.Width + 2f*style.CollisionBuffer.Width,
                                             size.Height + style.CollisionBuffer.Height*2f), style) 
                                { LabelPoint = position }; 
            }

            /*
            if (feature is LineString)
            {
                var line = feature as LineString;

                //Only label feature if it is long enough, or it is definately wanted                
                if (line.Length / map.PixelSize > size.Width || style.IgnoreLength)
                {
                    CalculateLabelOnLinestring(line, ref lbl, map);
                }
                else
                    return null;
            }
            */
            return lbl;
        }
Example #30
0
 private BaseLabel CreateLabel(Geometry feature, string text, float rotation, LabelStyle style, Map map, Graphics g)
 {
     return CreateLabel(feature, text, rotation, Priority, style, map, g);
 }
Example #31
0
        private IStyle calculateLabelStyle(IStyle min, IStyle max, Double value)
        {
            if (!(min is LabelStyle && max is LabelStyle))
            {
                throw new ArgumentException(
                    "Both min style and max style must be label styles to compute a gradient label style");
            }

            LabelStyle style = new LabelStyle();
            LabelStyle labelMin = min as LabelStyle;
            LabelStyle labelMax = max as LabelStyle;

			style.CollisionDetectionType = labelMin.CollisionDetectionType;
            style.Enabled = interpolateBool(min.Enabled, max.Enabled, value);

            Double fontSize = interpolateDouble(labelMin.Font.Size.Width, labelMax.Font.Size.Width, value);
            style.Font = new StyleFont(labelMin.Font.FontFamily, new Size2D(fontSize, fontSize), labelMin.Font.Style);

            if (labelMin.Background != null && labelMax.Background != null)
            {
                style.Background = interpolateBrush(labelMin.Background, labelMax.Background, value);
            }

            style.Foreground = interpolateBrush(labelMin.Foreground, labelMax.Foreground, value);

            if (labelMin.Halo != null && labelMax.Halo != null)
            {
                style.Halo = interpolatePen(labelMin.Halo, labelMax.Halo, value);
            }

            style.MinVisible = interpolateDouble(labelMin.MinVisible, labelMax.MinVisible, value);
            style.MaxVisible = interpolateDouble(labelMin.MaxVisible, labelMax.MaxVisible, value);
            style.Offset = new Point2D(interpolateDouble(labelMin.Offset.X, labelMax.Offset.X, value),
                                       interpolateDouble(labelMin.Offset.Y, labelMax.Offset.Y, value));

            return style;
        }
Example #32
0
        private static Label CreateLabel(Geometry feature, string text, float rotation, int priority, LabelStyle style, Map map,
                                  Graphics g)
        {
            //SizeF size = g.MeasureString(text, style.Font);

            SizeF size = VectorRenderer.SizeOfString(g, text, style.Font);
            //PointF position = map.WorldToImage(feature.GetBoundingBox().GetCentroid());
            PointF position = Transform.WorldtoMap(feature.GetBoundingBox().GetCentroid(), map);

            position.X = position.X - size.Width*(short) style.HorizontalAlignment*0.5f;
            position.Y = position.Y - size.Height*(short) (2-(int)style.VerticalAlignment)*0.5f;
            if (position.X - size.Width > map.Size.Width || position.X + size.Width < 0 ||
                position.Y - size.Height > map.Size.Height || position.Y + size.Height < 0)
                return null;

            Label lbl;
            if (!style.CollisionDetection)
                lbl = new Label(text, position, rotation, priority, null, style);
            else
            {
                //Collision detection is enabled so we need to measure the size of the string
                lbl = new Label(text, position, rotation, priority,
                                new LabelBox(position.X - size.Width*0.5f - style.CollisionBuffer.Width,
                                             position.Y + size.Height*0.5f + style.CollisionBuffer.Height,
                                             size.Width + 2f*style.CollisionBuffer.Width,
                                             size.Height + style.CollisionBuffer.Height*2f), style);
            }
            if (feature is LineString)
            {
                LineString line = feature as LineString;

                //Only label feature if it is long enough, or it is definately wanted                
                if (line.Length/map.PixelSize > size.Width || style.IgnoreLength)
                    CalculateLabelOnLinestring(line, ref lbl, map);
                else
                    return null;
            }

            return lbl;
        }
Example #33
0
 private static void SetLabelStyleProperties(LabelStyle labelStyle, ICssStyleDeclaration csd)
 {
     // Copy LabelStyle properties to the CSS declaration. Serializes:
     //   font-family        Font.Family
     //   font-size          Font.Size
     //   font-color         ForeColor
     //   background-color   BackColor
     //   border-color       Halo.Color
     //   border-width       Halo.Width
     //   padding-horizontal Offset.X
     //   padding-vertical   Offset.Y
     //   text-align         HorizontalAlignment
     //   vertical-align     VerticalAlignment
     LabelStyle labelDefaults = new LabelStyle();
     if (labelStyle.Font.FontFamily != labelDefaults.Font.FontFamily)
         csd.SetProperty("font-family", labelStyle.Font.FontFamily.Name, string.Empty);
     if (labelStyle.Font.Size != labelDefaults.Font.Size)
         csd.SetProperty("font-size", labelStyle.Font.Size.ToString("F0"), string.Empty);
     SetColorStyleProperty(csd, "font-color", labelStyle.ForeColor, labelDefaults.ForeColor);
     SetBrushStyleProperty(csd, "background-color", labelStyle.BackColor, labelDefaults.BackColor);
     SetColorStyleProperty(csd, "border-color", labelStyle.Halo.Color, labelDefaults.Halo.Color);
     if (labelStyle.Halo.Width != labelDefaults.Halo.Width)
         csd.SetProperty("border-width", labelStyle.Halo.Width.ToString("F0"), string.Empty);
     if (labelStyle.Offset.X != labelDefaults.Offset.X)
         csd.SetProperty("padding-horizontal", labelStyle.Offset.X.ToString("F0"), string.Empty);
     if (labelStyle.Offset.Y != labelDefaults.Offset.Y)
         csd.SetProperty("padding-vertical", labelStyle.Offset.Y.ToString("F0"), string.Empty);
     if (labelStyle.HorizontalAlignment != labelDefaults.HorizontalAlignment)
         csd.SetProperty("text-align", labelStyle.HorizontalAlignment.ToString(), string.Empty);
     if (labelStyle.VerticalAlignment != labelDefaults.VerticalAlignment)
         csd.SetProperty("vertical-align", labelStyle.VerticalAlignment.ToString(), string.Empty);
 }
Example #34
0
        /// <summary>
        /// Returns the style based on a feature
        /// </summary>
        /// <param name="attribute">Set of attribute values to calculate the <see cref="IStyle"/> from</param>
        /// <returns>The style</returns>
        public IStyle GetStyle(FeatureDataRow attribute)
        {
            // Do we have a theme to evaluate first?
            if (BaseTheme != null)
            {
                var style = BaseTheme.GetStyle(attribute);
                if (!style.Enabled) return style;
                if (!(style is LabelStyle)) return style;

                var labelStyle = (LabelStyle) style;
                return UpdateStyle(labelStyle, CalculateSize(_map, labelStyle.Font.SizeInPoints));
            }

            // Test if zoom level has changed.
            if (_currentZoom != _map.Zoom)
            {
                // Get the new size
                var newSize = CalculateSize(_map, _currentSize);
                
                // Update the style
                _currentStyle = UpdateStyle(_currentStyle, newSize);
                _currentZoom = _map.Zoom;
            }

            // return the style
            return _currentStyle;
        }
Example #35
0
        public static void DrawLabel(Graphics g, PointF labelPoint, PointF offset, Font font, Color forecolor,
                                     Brush backcolor, Pen halo, float rotation, string text, Map map,
                                     LabelStyle.HorizontalAlignmentEnum alignment = LabelStyle.HorizontalAlignmentEnum.Left,
                                     PointF? rotationPoint = null)

        {
            //Calculate the size of the text
            var labelSize = _sizeOfString(g, text, font);
            
            //Add label offset
            labelPoint.X += offset.X;
            labelPoint.Y += offset.Y;

            //Translate alignment to stringalignment
            StringAlignment salign;
            switch (alignment)
            {
                case LabelStyle.HorizontalAlignmentEnum.Left:
                    salign = StringAlignment.Near;
                    break;
                case LabelStyle.HorizontalAlignmentEnum.Center:
                    salign = StringAlignment.Center;
                    break;
                default:
                    salign = StringAlignment.Far;
                    break;
            }

            if (rotation != 0 && !float.IsNaN(rotation))
            {
                rotationPoint = rotationPoint ?? labelPoint;

                g.FillEllipse(Brushes.LawnGreen, rotationPoint.Value.X - 1, rotationPoint.Value.Y - 1, 2, 2);
                
                var t = g.Transform.Clone();
                g.TranslateTransform(rotationPoint.Value.X, rotationPoint.Value.Y);
                g.RotateTransform(rotation);
                //g.TranslateTransform(-labelSize.Width/2, -labelSize.Height/2);

                labelPoint = new PointF(labelPoint.X - rotationPoint.Value.X,
                                        labelPoint.Y - rotationPoint.Value.Y);

                //labelSize = new SizeF(labelSize.Width*0.74f + 1f, labelSize.Height*0.74f);
                if (backcolor != null && backcolor != Brushes.Transparent)
                    g.FillRectangle(backcolor, labelPoint.X, labelPoint.Y, labelSize.Width, labelSize.Height);

                var path = new GraphicsPath();
                path.AddString(text, font.FontFamily, (int) font.Style, font.Size,
                               new RectangleF(labelPoint, labelSize) /* labelPoint*/, 
                               new StringFormat { Alignment = salign } /*null*/);
                if (halo != null)
                    g.DrawPath(halo, path);

                g.FillPath(new SolidBrush(forecolor), path);
                //g.DrawString(text, font, new System.Drawing.SolidBrush(forecolor), 0, 0);        
                g.Transform = t;
            }
            else
            {
                if (backcolor != null && backcolor != Brushes.Transparent)
                    g.FillRectangle(backcolor, labelPoint.X, labelPoint.Y, labelSize.Width,
                                    labelSize.Height);

                var path = new GraphicsPath();
                path.AddString(text, font.FontFamily, (int) font.Style, font.Size, 
                               new RectangleF(labelPoint, labelSize) /* labelPoint*/,
                               new StringFormat { Alignment = salign } /*null*/);
                if (halo != null)
                    g.DrawPath(halo, path);
                g.FillPath(new SolidBrush(forecolor), path);
                //g.DrawString(text, font, new System.Drawing.SolidBrush(forecolor), LabelPoint.X, LabelPoint.Y);
            }
        }
        public static Map InitializeMap()
        {
            //Initialize a new map based on the simple map
              Map map = new Map();

              //Set up countries layer
              SharpMap.Layers.VectorLayer layCountries = new SharpMap.Layers.VectorLayer("Countries");
              //Set the datasource to a shapefile in the App_data folder
              layCountries.DataSource = new SharpMap.Data.Providers.ShapeFile("GeoData/World/countries.shp", true);
              //Set fill-style to green
              layCountries.Style.Fill = new SolidBrush(Color.Green);
              //Set the polygons to have a black outline
              layCountries.Style.Outline = System.Drawing.Pens.Black;
              layCountries.Style.EnableOutline = true;
              layCountries.SRID = 4326;
              map.Layers.Add(layCountries);

              //set up cities layer
              SharpMap.Layers.VectorLayer layCities = new SharpMap.Layers.VectorLayer("Cities");
              //Set the datasource to a shapefile in the App_data folder
              layCities.DataSource = new SharpMap.Data.Providers.ShapeFile("GeoData/World/cities.shp", true);
              layCities.Style.SymbolScale = 0.8f;
              layCities.MaxVisible = 40;
              layCities.SRID = 4326;
              map.Layers.Add(layCities);

              //Set up a country label layer
              SharpMap.Layers.LabelLayer layLabel = new SharpMap.Layers.LabelLayer("Country labels");
              layLabel.DataSource = layCountries.DataSource;
              layLabel.Enabled = true;
              layLabel.LabelColumn = "Name";
              layLabel.Style = new SharpMap.Styles.LabelStyle();
              layLabel.Style.ForeColor = Color.White;
              layLabel.Style.Font = new Font(FontFamily.GenericSerif, 12);
              layLabel.Style.BackColor = new System.Drawing.SolidBrush(Color.FromArgb(128, 255, 0, 0));
              layLabel.MaxVisible = 90;
              layLabel.MinVisible = 30;
              layLabel.Style.HorizontalAlignment = SharpMap.Styles.LabelStyle.HorizontalAlignmentEnum.Center;
              layLabel.SRID = 4326;
              layLabel.MultipartGeometryBehaviour = SharpMap.Layers.LabelLayer.MultipartGeometryBehaviourEnum.Largest;
              map.Layers.Add(layLabel);

              //Set up a city label layer
              SharpMap.Layers.LabelLayer layCityLabel = new SharpMap.Layers.LabelLayer("City labels");
              layCityLabel.DataSource = layCities.DataSource;
              layCityLabel.Enabled = true;
              layCityLabel.LabelColumn = "Name";
              layCityLabel.Style = new SharpMap.Styles.LabelStyle();
              layCityLabel.Style.ForeColor = Color.Black;
              layCityLabel.Style.Font = new Font(FontFamily.GenericSerif, 11);
              layCityLabel.MaxVisible = layLabel.MinVisible;
              layCityLabel.Style.HorizontalAlignment = SharpMap.Styles.LabelStyle.HorizontalAlignmentEnum.Left;
              layCityLabel.Style.VerticalAlignment = SharpMap.Styles.LabelStyle.VerticalAlignmentEnum.Bottom;
              layCityLabel.Style.Offset = new PointF(3, 3);
              layCityLabel.Style.Halo = new Pen(Color.Yellow, 2);
              layCityLabel.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
              layCityLabel.SmoothingMode = SmoothingMode.AntiAlias;
              layCityLabel.SRID = 4326;
              layCityLabel.LabelFilter = SharpMap.Rendering.LabelCollisionDetection.ThoroughCollisionDetection;
              layCityLabel.Style.CollisionDetection = true;
              map.Layers.Add(layCityLabel);

              //Set a gradient theme on the countries layer, based on Population density
              //First create two styles that specify min and max styles
              //In this case we will just use the default values and override the fill-colors
              //using a colorblender. If different line-widths, line- and fill-colors where used
              //in the min and max styles, these would automatically get linearly interpolated.
              VectorStyle min = new VectorStyle();
              VectorStyle max = new VectorStyle();
              //Create theme using a density from 0 (min) to 400 (max)
              GradientTheme popdens = new GradientTheme("PopDens", 0, 400, min, max);
              //We can make more advanced coloring using the ColorBlend'er.
              //Setting the FillColorBlend will override any fill-style in the min and max fills.
              //In this case we just use the predefined Rainbow colorscale
              popdens.FillColorBlend = SharpMap.Rendering.Thematics.ColorBlend.Rainbow5;
              layCountries.Theme = popdens;

              //Lets scale the labels so that big countries have larger texts as well
              LabelStyle lblMin = new LabelStyle();
              LabelStyle lblMax = new LabelStyle();
              lblMin.ForeColor = Color.Black;
              lblMin.Font = new Font(FontFamily.GenericSerif, 6);
              lblMax.ForeColor = Color.Blue;
              lblMax.BackColor = new SolidBrush(Color.FromArgb(128, 255, 255, 255));
              lblMin.BackColor = lblMax.BackColor;
              lblMax.Font = new Font(FontFamily.GenericSerif, 9);
              layLabel.Theme = new GradientTheme("PopDens", 0, 400, lblMin, lblMax);

              //Lets scale city icons based on city population
              //cities below 1.000.000 gets the smallest symbol, and cities with more than 5.000.000 the largest symbol
              VectorStyle citymin = new VectorStyle();
              VectorStyle citymax = new VectorStyle();
              string iconPath = "Images/icon.png";
              if (!File.Exists(iconPath))
              {
            throw new Exception(String.Format("Error file '{0}' could not be found, make sure it is at the expected location", iconPath));
              }

              citymin.Symbol = new Bitmap(iconPath);
              citymin.SymbolScale = 0.5f;
              citymax.Symbol = new Bitmap(iconPath);
              citymax.SymbolScale = 1f;
              layCities.Theme = new GradientTheme("Population", 1000000, 5000000, citymin, citymax);

              //limit the zoom to 360 degrees width
              map.MaximumZoom = 360;
              map.BackColor = Color.LightBlue;

              map.Zoom = 30;
              map.Center = new SharpMap.Geometries.Point(0, 0);

              return map;
        }
Example #37
0
	    protected LabelStyle(LabelStyle another) : base(another)
	    {
	        _Font = (Font) another.Font.Clone();
	        _Offset = another.Offset;
	        _CollisionDetection = another.CollisionDetection;
	        _CollisionBuffer = another.CollisionBuffer;
	        _ForeColor = another.ForeColor;

	        if (another.BackColor != null && another.BackColor is SolidBrush)
	        {
	            _BackColor = new SolidBrush((another.BackColor as SolidBrush).Color);
	        }
	        if (another.Halo != null)
	        {
	            _Halo = new Pen(another.Halo.Color, another.Halo.Width);
	        }
	        
	        _Offset = another._Offset;
            _HorisontalAlignment = another.HorizontalAlignment;
            _VerticalAlignment = another.VerticalAlignment;
	    }