SharpMap是一個基於.NET Framework 4,采用C#開發的地圖渲染引擎,非常易於使用。本教程針對SharpMap入門及開發,講述如何基於SharpMap組件渲染Shapefile數據。
一、添加SharpMap的UI組件至VS工具箱
添加后如圖所示
二、加載Shapefile圖層數據
1、給WinForm窗體添加MapBox組件
2、為項目添加SharpMap引用,一般來說給WinForm窗體添加MapBox組件后,會自動引用SharpMap引用,如果沒有的話,手動添加SharpMap.dll引用
3、在WinForm窗體構造器方法中添加如下代碼,實現加載Shapefile數據
SharpMap.Layers.VectorLayer vlay = new SharpMap.Layers.VectorLayer("States"); vlay.DataSource = new SharpMap.Data.Providers.ShapeFile("ShpData\\Provinces_R.shp", true); mapBox1.Map.Layers.Add(vlay); mapBox1.Map.ZoomToExtents(); mapBox1.Refresh();
4、設置當前地圖工具為Pan(漫游)
mapBox1.ActiveTool = SharpMap.Forms.MapBox.Tools.Pan;
運行結果如下(默認的渲染樣式比較丑)
三、根據要素屬性唯一值渲染圖層
該圖層的id字段取值為[1,2,3,4],為每一種類型設置不同的渲染風格,指定按id字段唯一值進行渲染
VectorStyle style1 = new VectorStyle(); style1.Fill = new SolidBrush(Color.FromArgb(204, 89, 68)); style1.EnableOutline = true; style1.Outline = new Pen(Brushes.Black, 1.2f); VectorStyle style2 = new VectorStyle(); style2.Fill = new SolidBrush(Color.FromArgb(253, 174, 97)); style2.EnableOutline = true; style2.Outline = new Pen(Brushes.Black, 1.2f); VectorStyle style3 = new VectorStyle(); style3.Fill = new SolidBrush(Color.FromArgb(255, 255, 192)); style3.EnableOutline = true; style3.Outline = new Pen(Brushes.Black, 1.2f); VectorStyle style4 = new VectorStyle(); style4.Fill = new SolidBrush(Color.FromArgb(166, 217, 106)); style4.EnableOutline = true; style4.Outline = new Pen(Brushes.Black, 1.2f); Dictionary<string, SharpMap.Styles.IStyle> styles = new Dictionary<string, IStyle>(); styles.Add("1", style1); styles.Add("2", style2); styles.Add("3", style3); styles.Add("4", style4); vlay.Theme = new SharpMap.Rendering.Thematics.UniqueValuesTheme<string>("id", styles, style1);
運行結果如下
渲染效果還不錯吧,比默認樣式好看多了 :)