掌握 SharpMap 進階客製化:依屬性值著色、自訂標籤內容與多欄位顯示、標籤字體隨縮放層級動態調整。
使用 CustomTheme 配合委托方法:
SharpMap.Rendering.Thematics.CustomTheme iTheme =
new SharpMap.Rendering.Thematics.CustomTheme(GetMyStyle);
委托實作:
private static SharpMap.Styles.VectorStyle GetMyStyle(SharpMap.Data.FeatureDataRow row) {
var style = new SharpMap.Styles.VectorStyle();
switch (row["Status"].ToString().ToLower()) {
case "available":
style.Fill = Brushes.Yellow; // 可用→黃色
break;
default:
style.Fill = Brushes.Green; // 其他→綠色
break;
}
return style;
}
效果圖:

SharpMap.Layers.LabelLayer myLabel = new SharpMap.Layers.LabelLayer("labels");
myLabel.DataSource = myLayer.DataSource;
myLabel.LabelStringDelegate = new SharpMap.Layers.LabelLayer.GetLabelMethod(GetLabelString);
委托實作:
public static string GetLabelString(FeatureDataRow dr) {
string field1 = dr["HouseNumber"]?.ToString() ?? "";
string field2 = dr["HostName"]?.ToString() ?? "";
string field3 = dr["Memo"]?.ToString() ?? "";
return $"{field1}: {field2}\r\n{field3}";
}
注意:換行需用 \r\n,不支援 HTML 標籤。
public void ChangeFontSize(double Zoom, SharpMap.Layers.ILayer iLayer) {
var labelLayer = (SharpMap.Layers.LabelLayer)iLayer;
if (Zoom < 800 && Zoom > 400) labelLayer.Style.Font = new Font(FontFamily.GenericSerif, 6);
else if (Zoom < 400 && Zoom > 140) labelLayer.Style.Font = new Font(FontFamily.GenericSerif, 8);
else if (Zoom < 140 && Zoom > 20) labelLayer.Style.Font = new Font(FontFamily.GenericSerif, 16);
else if (Zoom < 20) labelLayer.Style.Font = new Font(FontFamily.GenericSerif, 48);
else labelLayer.Style.Font = new Font(FontFamily.GenericSerif, 70);
}
前端 AJAX 控件的 zoomAmount 屬性記錄縮放倍數,Handler 中取得 Zoom 參數並呼叫:
ChangeFontSize(Zoom, map.GetLayerByName("mylabels"));
將 LabelStringDelegate 指派放入對應的 if-else 區塊即可實現不同縮放層級顯示不同詳細度的標籤內容。
透過 CustomTheme、LabelStringDelegate 與縮放事件處理,實現了專業 GIS 應用中常見的:分級著色、豐富標籤、自適應字體三大核心視覺化需求。