/// <summary> /// Renders the polygon to a bitmap. /// </summary> /// <param name="poly">The polygon.</param> /// <param name="width">The desired width (pixel) of the image.</param> /// <returns>The bitmap.</returns> /// <remarks> /// The width has to be at least 2 * sqrt(n), n the number of vertices. /// Otherwise, an empty bitmap /// </remarks> public Bitmap Render(Geometry.IPolygon poly, int width = 800) { Bitmap bitmap; // Check if the specified width is reasonable if (width < 2 * Math.Sqrt(poly.Points.Count)) { return(new Bitmap(1, 1)); } var bounds = poly.Bounds(); // World margin on each side float margin = (float)bounds.Height * 0.05f; float scale = width / ((float)bounds.Width + 2 * margin); var target = new Rectangle(0, 0, width, (int)((bounds.Height + 2 * margin) * scale)); bitmap = new Bitmap(width, target.Height, PixelFormat.Format32bppPArgb); using (var g = Graphics.FromImage(bitmap)) { g.Clear(colors.Background); g.SmoothingMode = SmoothingMode.HighQuality; var context = new RenderContext(new Projection(target), colors); context.Add(poly); if (!EnablePoints) { context.Enable(3, false); } var renderer = new LayerRenderer(); renderer.Context = context; renderer.RenderTarget = g; renderer.Render(); } return(bitmap); }
/// <summary> /// Exports a polygon to PNG format. /// </summary> /// <param name="poly">The polygon.</param> /// <param name="width">The desired width (pixel) of the image.</param> /// <param name="file">The PNG filename.</param> /// <param name="regions">Enable rendering of regions.</param> /// <param name="points">Enable rendering of points.</param> public static void Save(Geometry.IPolygon poly, string file = null, int width = 800, bool points = true) { // Check file name if (string.IsNullOrWhiteSpace(file)) { file = string.Format("poly-{0}.png", DateTime.Now.ToString("yyyy-M-d-hh-mm-ss")); } // Ensure .png extension. if (file.EndsWith(".png", StringComparison.OrdinalIgnoreCase)) { Path.ChangeExtension(file, ".png"); } var renderer = new ImageRenderer(); renderer.EnableRegions = false; renderer.EnablePoints = points; var bitmap = renderer.Render(poly, width); bitmap.Save(file, ImageFormat.Png); }