1. SharpMap中屏幕坐标和地图Map坐标转换:
1 using System.Drawing;
2 using GeoAPI.Geometries;
3
4 namespace SharpMap.Utilities
5 {
6 /// <summary>
7 /// Class for transforming between world and image coordinate
8 /// </summary>
9 public class Transform
10 {
11 /// <summary>
12 /// Transforms from world coordinate system (WCS) to image coordinates
13 /// 将世界坐标转换为image坐标
14 /// NOTE: This method DOES NOT take the MapTransform property into account (use <see cref="Map.WorldToImage(GeoAPI.Geometries.Coordinate,bool)"/> instead)
15 /// </summary>
16 /// <param name="p">Point in WCS</param>
17 /// <param name="map">Map reference</param>
18 /// <returns>Point in image coordinates</returns>
19 public static PointF WorldtoMap(Coordinate p, Map map)
20 {
21 //if (map.MapTransform != null && !map.MapTransform.IsIdentity)
22 // map.MapTransform.TransformPoints(new System.Drawing.PointF[] { p });
23 if (p.IsEmpty())
24 return PointF.Empty;
25
26 var result = new PointF();
27
28 var height = (map.Zoom * map.Size.Height) / map.Size.Width;
29 var left = map.Center.X - map.Zoom * 0.5;
30 var top = map.Center.Y + height * 0.5 * map.PixelAspectRatio;
31 result.X = (float)((p.X - left) / map.PixelWidth);
32 result.Y = (float)((top - p.Y) / map.PixelHeight);
33 if (double.IsNaN(result.X) || double.IsNaN(result.Y))
34 result = PointF.Empty;
35 return result;
36 }
37
38 /// <summary>
39 /// Transforms from image coordinates to world coordinate system (WCS).
40 /// NOTE: This method DOES NOT take the MapTransform property into account (use <see cref="Map.ImageToWorld(System.Drawing.PointF,bool)"/> instead)
41 /// </summary>
42 /// <param name="p">Point in image coordinate system</param>
43 /// <param name="map">Map reference</param>
44 /// <returns>Point in WCS</returns>
45 public static Coordinate MapToWorld(PointF p, Map map)
46 {
47 if (map.Center.IsEmpty() || double.IsNaN(map.MapHeight))
48 {
49 return new Coordinate(0, 0);
50 }
51 var ul = new Coordinate(map.Center.X - map.Zoom * .5, map.Center.Y + map.MapHeight * .5);
52 return new Coordinate(ul.X + p.X * map.PixelWidth,
53 ul.Y - p.Y * map.PixelHeight);
54 }
55 }
56 }
详细分析: http://www.cnblogs.com/yhlx125/archive/2012/02/10/2342282.html
2. OpenS-CAD中的实现
已知屏幕分辨率每英寸像素点数,一般为96dpi, 定义float m_screenResolution = 96;
1. 初始化CanvasCtrl时,首先调用OnResize()方法。
1 protected override void OnResize(EventArgs e) 2 { 3 base.OnResize(e); 4 5 if (m_lastCenterPoint != UnitPoint.Empty && Width != 0) 6 SetCenterScreen(ToScreen(m_lastCenterPoint), false); 7 m_lastCenterPoint = CenterPointUnit(); 8 m_staticImage = null; 9 DoInvalidate(true); 10 }