public void Render(PlotDimensions dims, Bitmap bmp, bool lowQuality = false) { using (Graphics gfx = Graphics.FromImage(bmp)) { gfx.SmoothingMode = lowQuality ? SmoothingMode.HighSpeed : SmoothingMode.AntiAlias; gfx.TextRenderingHint = lowQuality ? TextRenderingHint.SingleBitPerPixelGridFit : TextRenderingHint.AntiAliasGridFit; for (int barIndex = 0; barIndex < ys.Length; barIndex++) { if (verticalBars) { RenderBarVertical(dims, gfx, xs[barIndex] + xOffset, ys[barIndex], yErr[barIndex], yOffsets[barIndex]); } else { RenderBarHorizontal(dims, gfx, xs[barIndex] + xOffset, ys[barIndex], yErr[barIndex], yOffsets[barIndex]); } } } }
private void RenderBeforePlottables(Bitmap bmp, bool lowQuality, PlotDimensions dims) { settings.DataBackground.Render(dims, bmp, lowQuality); foreach (var axis in settings.Axes) { PlotDimensions dims2 = axis.IsHorizontal ? settings.GetPlotDimensions(axis.AxisIndex, 0, dims.ScaleFactor) : settings.GetPlotDimensions(0, axis.AxisIndex, dims.ScaleFactor); try { axis.Render(dims2, bmp, lowQuality); } catch (OverflowException) { throw new InvalidOperationException("data cannot contain Infinity"); } } }
private void RenderAfterPlottables(Bitmap bmp, bool lowQuality, PlotDimensions dims) { if (settings.DrawGridAbovePlottables) { RenderAxes(bmp, lowQuality, dims); } settings.CornerLegend.UpdateLegendItems(this); if (settings.CornerLegend.IsVisible) { settings.CornerLegend.Render(dims, bmp, lowQuality); } settings.BenchmarkMessage.Stop(); settings.ZoomRectangle.Render(dims, bmp, lowQuality); settings.BenchmarkMessage.Render(dims, bmp, lowQuality); settings.ErrorMessage.Render(dims, bmp, lowQuality); }
public void Render(PlotDimensions dims, Bitmap bmp, bool lowQuality = false) { PointF defaultPoint = new PointF(dims.GetPixelX(x), dims.GetPixelY(y)); PointF textLocationPoint = (rotation == 0) ? TextLocation(defaultPoint) : defaultPoint; using (Graphics gfx = GDI.Graphics(bmp, lowQuality)) using (var framePen = new Pen(frameColor, frameSize * 2)) { gfx.TranslateTransform((int)textLocationPoint.X, (int)textLocationPoint.Y); gfx.RotateTransform((float)rotation); if (frameSize > 0) { gfx.DrawRectangle(framePen, new Rectangle(0, 0, image.Width - 1, image.Height - 1)); } gfx.DrawImage(image, new PointF(0, 0)); gfx.ResetTransform(); } }
public void Render(PlotDimensions dims, Bitmap bmp, bool lowQuality = false) { using (Graphics gfx = GDI.Graphics(bmp, lowQuality)) using (Pen pen = GDI.Pen(Color.Black)) { pen.CustomEndCap = new AdjustableArrowCap(2, 2); for (int i = 0; i < xs.Length; i++) { for (int j = 0; j < ys.Length; j++) { Vector2 v = vectors[i, j]; float tailX = dims.GetPixelX(xs[i] - v.X / 2); float tailY = dims.GetPixelY(ys[j] - v.Y / 2); float endX = dims.GetPixelX(xs[i] + v.X / 2); float endY = dims.GetPixelY(v.Y + ys[j] - v.Y / 2); pen.Color = arrowColors[i * ys.Length + j]; gfx.DrawLine(pen, tailX, tailY, endX, endY); } } } }
public void Render(PlotDimensions dims, Bitmap bmp, bool lowQuality = false) { using (var gfx = GDI.Graphics(bmp, lowQuality)) using (var pen = GDI.Pen(color, lineWidth, lineStyle, true)) { if (IsHorizontal) { float pixelX1 = dims.GetPixelX(dims.XMin); float pixelX2 = dims.GetPixelX(dims.XMax); float pixelY = dims.GetPixelY(position); gfx.DrawLine(pen, pixelX1, pixelY, pixelX2, pixelY); } else { float pixelX = dims.GetPixelX(position); float pixelY1 = dims.GetPixelY(dims.YMin); float pixelY2 = dims.GetPixelY(dims.YMax); gfx.DrawLine(pen, pixelX, pixelY1, pixelX, pixelY2); } } }
public new void Render(PlotDimensions dims, Bitmap bmp, bool lowQuality = false) { base.Render(dims, bmp, lowQuality); if (isHighlighted is null || isHighlighted.Length == 0) { return; } using (var gfx = Graphics.FromImage(bmp)) { gfx.SmoothingMode = lowQuality ? SmoothingMode.HighSpeed : SmoothingMode.AntiAlias; gfx.TextRenderingHint = lowQuality ? TextRenderingHint.SingleBitPerPixelGridFit : TextRenderingHint.AntiAliasGridFit; var highlightedIndexes = Enumerable.Range(0, isHighlighted.Length).Where(x => isHighlighted[x]); foreach (int i in highlightedIndexes) { PointF pt = new PointF(dims.GetPixelX(xs[i]), dims.GetPixelY(ys[i])); MarkerTools.DrawMarker(gfx, pt, highlightedShape, highlightedMarkerSize, highlightedColor); } } }
private void RenderPlottables(Bitmap bmp, bool lowQuality, double scaleFactor) { foreach (var plottable in settings.Plottables) { if (plottable.IsVisible == false) { continue; } plottable.ValidateData(deep: false); PlotDimensions dims = (plottable is Plottable.IPlottable p) ? settings.GetPlotDimensions(p.XAxisIndex, p.YAxisIndex, scaleFactor) : settings.GetPlotDimensions(0, 0, scaleFactor); if (double.IsInfinity(dims.XSpan) || double.IsInfinity(dims.YSpan)) { throw new InvalidOperationException($"Axis limits cannot be infinite: {dims}"); } try { plottable.Render(dims, bmp, lowQuality); } catch (OverflowException ex) { // This exception is commonly thrown by System.Drawing when drawing to extremely large pixel locations. if (settings.IgnoreOverflowExceptionsDuringRender) { Debug.WriteLine($"OverflowException plotting: {plottable}"); } else { throw new OverflowException("overflow during render", ex); } } } }
public static void Scatter(PlotDimensions dims, Bitmap bmp, bool lowQuality, Population pop, Random rand, double popLeft, double popWidth, Color fillColor, Color edgeColor, byte alpha, Position position) { // adjust edges to accomodate special positions if (position == Position.Hide) { return; } if (position == Position.Left || position == Position.Right) { popWidth /= 2; } if (position == Position.Right) { popLeft += popWidth; } // contract edges slightly to encourage padding between elements double edgePaddingFrac = 0.2; popLeft += popWidth * edgePaddingFrac; popWidth -= (popWidth * edgePaddingFrac) * 2; float radius = 5; using (Graphics gfx = GDI.Graphics(bmp, lowQuality)) using (Pen penEdge = GDI.Pen(Color.FromArgb(alpha, edgeColor))) using (Brush brushFill = GDI.Brush(Color.FromArgb(alpha, fillColor))) { foreach (double value in pop.values) { double yPx = dims.GetPixelY(value); double xPx = dims.GetPixelX(popLeft + rand.NextDouble() * popWidth); gfx.FillEllipse(brushFill, (float)(xPx - radius), (float)(yPx - radius), radius * 2, radius * 2); gfx.DrawEllipse(penEdge, (float)(xPx - radius), (float)(yPx - radius), radius * 2, radius * 2); } } }
public void Render(PlotDimensions dims, Bitmap bmp, bool lowQuality = false) { using (Graphics gfx = Graphics.FromImage(bmp)) using (var pen = GDI.Pen(Color, LineWidth, LineStyle, true)) { if (XErrorPositive != null) { DrawErrorBar(dims, gfx, pen, XErrorPositive, true, true); } if (XErrorNegative != null) { DrawErrorBar(dims, gfx, pen, XErrorNegative, true, false); } if (YErrorPositive != null) { DrawErrorBar(dims, gfx, pen, YErrorPositive, false, true); } if (YErrorNegative != null) { DrawErrorBar(dims, gfx, pen, YErrorNegative, false, false); } } }
private void RenderPlottables(Bitmap bmp, bool lowQuality) { foreach (var plottable in settings.Plottables) { if (plottable.IsVisible == false) { continue; } PlotDimensions dims = (plottable is Plottable.IUsesAxes p) ? settings.GetPlotDimensions(p.HorizontalAxisIndex, p.VerticalAxisIndex) : settings.GetPlotDimensions(0, 0); try { plottable.Render(dims, bmp, lowQuality); } catch (OverflowException) { Debug.WriteLine($"OverflowException plotting: {plottable}"); } } }
public void Render(PlotDimensions dims, Bitmap bmp, bool lowQuality = false) { PointF[] points = new PointF[xs.Length]; for (int i = 0; i < xs.Length; i++) { points[i] = new PointF(dims.GetPixelX(xs[i]), dims.GetPixelY(ys[i])); } using (Graphics gfx = GDI.Graphics(bmp, lowQuality)) using (Brush fillBrush = GDI.Brush(Color.FromArgb((byte)(255 * fillAlpha), fillColor))) using (Pen outlinePen = GDI.Pen(lineColor, (float)lineWidth)) { if (fill) { gfx.FillPolygon(fillBrush, points); } if (lineWidth > 0) { gfx.DrawPolygon(outlinePen, points); } } }
private void RenderAxis(PlotDimensions dims, Bitmap bmp, bool lowQuality) { using (Graphics gfx = GDI.Graphics(bmp, lowQuality)) using (Pen pen = GDI.Pen(Color.Black)) using (Brush brush = GDI.Brush(Color.Black)) using (Font axisFont = GDI.Font(null, 12)) using (StringFormat right_centre = new StringFormat() { Alignment = StringAlignment.Far, LineAlignment = StringAlignment.Center }) using (StringFormat centre_top = new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Near }) { double offset = -2; double minScale = Math.Min(dims.PxPerUnitX, dims.PxPerUnitY); gfx.DrawString($"{AxisOffsets[0]:f3}", axisFont, brush, dims.GetPixelX(0), dims.GetPixelY(offset), centre_top); gfx.DrawString($"{AxisOffsets[0] + AxisMultipliers[0]:f3}", axisFont, brush, new PointF((float)((width * minScale) + dims.GetPixelX(0)), dims.GetPixelY(offset)), centre_top); gfx.DrawString($"{AxisOffsets[1]:f3}", axisFont, brush, dims.GetPixelX(offset), dims.GetPixelY(0), right_centre); gfx.DrawString($"{AxisOffsets[1] + AxisMultipliers[1]:f3}", axisFont, brush, new PointF(dims.GetPixelX(offset), dims.GetPixelY(0) - (float)(height * minScale)), right_centre); } }
public static void DataPlottables(Settings settings) { if (settings.gfxData == null) { return; } // Construct the dimensions object to be injected into plottables during rendering. var dims = new PlotDimensions(settings.figureSize, settings.dataSize, settings.dataOrigin, settings.axes.Limits); bool lowQuality = !settings.misc.antiAliasData; for (int i = 0; i < settings.plottables.Count; i++) { Plottable plottable = settings.plottables[i]; if (plottable.visible) { try { if (plottable is IPlottable modernPlottable) { // use the new render method (that injections dimensions and the bitmap to draw on) modernPlottable.Render(dims, settings.bmpData, lowQuality); } else { // use the old render method (that reads state from settings module and draws on the bitmap stored there) plottable.Render(settings); } } catch (OverflowException) { Debug.WriteLine($"OverflowException plotting: {plottable}"); } } } }
public void Render(PlotDimensions dims, Bitmap bmp, bool lowQuality = false) { using (var gfx = Graphics.FromImage(bmp)) using (var font = GDI.Font(FontName, FontSize, FontBold)) using (var fontBrush = new SolidBrush(FontColor)) using (var shadowBrush = new SolidBrush(ShadowColor)) using (var backgroundBrush = new SolidBrush(BackgroundColor)) using (var borderPen = new Pen(BorderColor, BorderWidth)) { gfx.SmoothingMode = lowQuality ? SmoothingMode.HighSpeed : SmoothingMode.AntiAlias; gfx.TextRenderingHint = lowQuality ? TextRenderingHint.SingleBitPerPixelGridFit : TextRenderingHint.AntiAliasGridFit; SizeF size = GDI.MeasureString(gfx, label, font); double x = (xPixel >= 0) ? xPixel : dims.DataWidth + xPixel - size.Width; double y = (yPixel >= 0) ? yPixel : dims.DataHeight + yPixel - size.Height; PointF location = new PointF((float)x, (float)y); if (Background && Shadow) { gfx.FillRectangle(shadowBrush, location.X + 5, location.Y + 5, size.Width, size.Height); } if (Background) { gfx.FillRectangle(backgroundBrush, location.X, location.Y, size.Width, size.Height); } if (Border) { gfx.DrawRectangle(borderPen, location.X, location.Y, size.Width, size.Height); } gfx.DrawString(label, font, fontBrush, location); } }
private void LayoutAuto(int xAxisIndex, int yAxisIndex) { // TODO: separate this into distinct X and Y functions (requires refactoring plottable interface) bool atLeastOneAxisIsZero = xAxisIndex == 0 || yAxisIndex == 0; if (!atLeastOneAxisIsZero) { throw new InvalidOperationException(); } // Adjust padding around the data area to accommodate title and tick labels. // // This is a chicken-and-egg problem: // * TICK DENSITY depends on the DATA AREA SIZE // * DATA AREA SIZE depends on LAYOUT PADDING // * LAYOUT PADDING depends on MAXIMUM LABEL SIZE // * MAXIMUM LABEL SIZE depends on TICK DENSITY // // To solve this, start by assuming data area size == figure size and layout padding == 0, // then calculate ticks, then set padding based on the largest tick, then re-calculate ticks. // axis limits shall not change var dims = GetPlotDimensions(xAxisIndex, yAxisIndex); var limits = (dims.XMin, dims.XMax, dims.YMin, dims.YMax); var figSize = new SizeF(Width, Height); // first-pass tick calculation based on full image size var dimsFull = new PlotDimensions(figSize, figSize, new PointF(0, 0), limits); foreach (var axis in Axes) { bool isMatchingXAxis = axis.IsHorizontal && axis.AxisIndex == xAxisIndex; bool isMatchingYAxis = axis.IsVertical && axis.AxisIndex == yAxisIndex; if (isMatchingXAxis || isMatchingYAxis) { axis.RecalculateTickPositions(dimsFull); axis.RecalculateAxisSize(); } } // now adjust our layout based on measured axis sizes RecalculateDataPadding(); // now recalculate ticks based on new layout var dataSize = new SizeF(DataWidth, DataHeight); var dataOffset = new PointF(DataOffsetX, DataOffsetY); var dims3 = new PlotDimensions(figSize, dataSize, dataOffset, limits); foreach (var axis in Axes) { bool isMatchingXAxis = axis.IsHorizontal && axis.AxisIndex == xAxisIndex; bool isMatchingYAxis = axis.IsVertical && axis.AxisIndex == yAxisIndex; if (isMatchingXAxis || isMatchingYAxis) { axis.RecalculateTickPositions(dims3); } } // adjust the layout based on measured tick label sizes RecalculateDataPadding(); }
private void RenderClear(Bitmap bmp, bool lowQuality, PlotDimensions primaryDims) { settings.FigureBackground.Render(primaryDims, bmp, lowQuality); }
public static void Box(PlotDimensions dims, Bitmap bmp, bool lowQuality, Population pop, Random rand, double popLeft, double popWidth, Color color, Position position, BoxFormat boxFormat, HorizontalAlignment errorAlignment = HorizontalAlignment.Right) { // adjust edges to accomodate special positions if (position == Position.Hide) { return; } if (position == Position.Left || position == Position.Right) { popWidth /= 2; } if (position == Position.Right) { popLeft += popWidth; } double errorMaxPx, errorMinPx; double yPxTop, yPxBase; double yPx; if (boxFormat == BoxFormat.StdevStderrMean) { errorMaxPx = dims.GetPixelY(pop.mean + pop.stDev); errorMinPx = dims.GetPixelY(pop.mean - pop.stDev); yPxTop = dims.GetPixelY(pop.mean + pop.stdErr); yPxBase = dims.GetPixelY(pop.mean - pop.stdErr); yPx = dims.GetPixelY(pop.mean); } else if (boxFormat == BoxFormat.OutlierQuartileMedian) { errorMaxPx = dims.GetPixelY(pop.maxNonOutlier); errorMinPx = dims.GetPixelY(pop.minNonOutlier); yPxTop = dims.GetPixelY(pop.Q3); yPxBase = dims.GetPixelY(pop.Q1); yPx = dims.GetPixelY(pop.median); } else { throw new NotImplementedException(); } // make cap width a fraction of available space double capWidthFrac = .38; double capWidth = popWidth * capWidthFrac; // contract edges slightly to encourage padding between elements double edgePaddingFrac = 0.2; popLeft += popWidth * edgePaddingFrac; popWidth -= (popWidth * edgePaddingFrac) * 2; double leftPx = dims.GetPixelX(popLeft); double rightPx = dims.GetPixelX(popLeft + popWidth); RectangleF rect = new RectangleF( x: (float)leftPx, y: (float)yPxTop, width: (float)(rightPx - leftPx), height: (float)(yPxBase - yPxTop)); // determine location of errorbars and caps double capPx1, capPx2, errorPxX; switch (errorAlignment) { case HorizontalAlignment.Center: double centerX = popLeft + popWidth / 2; errorPxX = dims.GetPixelX(centerX); capPx1 = dims.GetPixelX(centerX - capWidth / 2); capPx2 = dims.GetPixelX(centerX + capWidth / 2); break; case HorizontalAlignment.Right: errorPxX = dims.GetPixelX(popLeft + popWidth); capPx1 = dims.GetPixelX(popLeft + popWidth - capWidth / 2); capPx2 = dims.GetPixelX(popLeft + popWidth); break; case HorizontalAlignment.Left: errorPxX = dims.GetPixelX(popLeft); capPx1 = dims.GetPixelX(popLeft); capPx2 = dims.GetPixelX(popLeft + capWidth / 2); break; default: throw new NotImplementedException(); } using (Graphics gfx = GDI.Graphics(bmp, lowQuality)) using (Pen pen = GDI.Pen(Color.Black)) using (Brush brush = GDI.Brush(color)) { // draw the box gfx.FillRectangle(brush, rect.X, rect.Y, rect.Width, rect.Height); gfx.DrawRectangle(pen, rect.X, rect.Y, rect.Width, rect.Height); // draw the line in the center gfx.DrawLine(pen, rect.X, (float)yPx, rect.X + rect.Width, (float)yPx); // draw errorbars and caps gfx.DrawLine(pen, (float)errorPxX, (float)errorMinPx, (float)errorPxX, rect.Y + rect.Height); gfx.DrawLine(pen, (float)errorPxX, (float)errorMaxPx, (float)errorPxX, rect.Y); gfx.DrawLine(pen, (float)capPx1, (float)errorMinPx, (float)capPx2, (float)errorMinPx); gfx.DrawLine(pen, (float)capPx1, (float)errorMaxPx, (float)capPx2, (float)errorMaxPx); } }
public static void Bar(PlotDimensions dims, Bitmap bmp, bool lowQuality, Population pop, Random rand, double popLeft, double popWidth, Color color, Position position, bool useStdErr = false) { // adjust edges to accomodate special positions if (position == Position.Hide) { return; } if (position == Position.Left || position == Position.Right) { popWidth /= 2; } if (position == Position.Right) { popLeft += popWidth; } // determine the center point and calculate bounds double centerX = popLeft + popWidth / 2; double xPx = dims.GetPixelX(centerX); double yPxTop = dims.GetPixelY(pop.mean); double yPxBase = dims.GetPixelY(0); double errorMaxPx, errorMinPx; if (useStdErr) { errorMaxPx = dims.GetPixelY(pop.mean + pop.stdErr); errorMinPx = dims.GetPixelY(pop.mean - pop.stdErr); } else { errorMaxPx = dims.GetPixelY(pop.mean + pop.stDev); errorMinPx = dims.GetPixelY(pop.mean - pop.stDev); } // make cap width a fraction of available space double capWidthFrac = .38; double capWidth = popWidth * capWidthFrac; double capPx1 = dims.GetPixelX(centerX - capWidth / 2); double capPx2 = dims.GetPixelX(centerX + capWidth / 2); // contract edges slightly to encourage padding between elements double edgePaddingFrac = 0.2; popLeft += popWidth * edgePaddingFrac; popWidth -= (popWidth * edgePaddingFrac) * 2; double leftPx = dims.GetPixelX(popLeft); double rightPx = dims.GetPixelX(popLeft + popWidth); RectangleF rect = new RectangleF((float)leftPx, (float)yPxTop, (float)(rightPx - leftPx), (float)(yPxBase - yPxTop)); using (Graphics gfx = GDI.Graphics(bmp, lowQuality)) using (Pen pen = GDI.Pen(Color.Black)) using (Brush brush = GDI.Brush(color)) { gfx.FillRectangle(brush, rect.X, rect.Y, rect.Width, rect.Height); gfx.DrawRectangle(pen, rect.X, rect.Y, rect.Width, rect.Height); gfx.DrawLine(pen, (float)xPx, (float)errorMinPx, (float)xPx, (float)errorMaxPx); gfx.DrawLine(pen, (float)capPx1, (float)errorMinPx, (float)capPx2, (float)errorMinPx); gfx.DrawLine(pen, (float)capPx1, (float)errorMaxPx, (float)capPx2, (float)errorMaxPx); } }
public void Render(PlotDimensions dims, Bitmap bmp, bool lowQuality = false) { Random rand = new Random(0); double groupWidth = .8; var popWidth = groupWidth / seriesCount; for (int seriesIndex = 0; seriesIndex < seriesCount; seriesIndex++) { for (int groupIndex = 0; groupIndex < groupCount; groupIndex++) { var series = popMultiSeries.multiSeries[seriesIndex]; var population = series.populations[groupIndex]; var groupLeft = groupIndex - groupWidth / 2; var popLeft = groupLeft + popWidth * seriesIndex; Position scatterPos, boxPos; switch (displayItems) { case DisplayItems.BoxAndScatter: boxPos = Position.Left; scatterPos = Position.Right; break; case DisplayItems.BoxOnly: boxPos = Position.Center; scatterPos = Position.Hide; break; case DisplayItems.ScatterAndBox: boxPos = Position.Right; scatterPos = Position.Left; break; case DisplayItems.ScatterOnly: boxPos = Position.Hide; scatterPos = Position.Center; break; default: throw new NotImplementedException(); } Scatter(dims, bmp, lowQuality, population, rand, popLeft, popWidth, series.color, scatterOutlineColor, 128, scatterPos); if (displayDistributionCurve) { Distribution(dims, bmp, lowQuality, population, rand, popLeft, popWidth, distributionCurveColor, scatterPos, distributionCurveLineStyle); } switch (boxStyle) { case BoxStyle.BarMeanStdErr: Bar(dims, bmp, lowQuality, population, rand, popLeft, popWidth, series.color, boxPos, useStdErr: true); break; case BoxStyle.BarMeanStDev: Bar(dims, bmp, lowQuality, population, rand, popLeft, popWidth, series.color, boxPos, useStdErr: false); break; case BoxStyle.BoxMeanStdevStderr: Box(dims, bmp, lowQuality, population, rand, popLeft, popWidth, series.color, boxPos, BoxFormat.StdevStderrMean); break; case BoxStyle.BoxMedianQuartileOutlier: Box(dims, bmp, lowQuality, population, rand, popLeft, popWidth, series.color, boxPos, BoxFormat.OutlierQuartileMedian); break; case BoxStyle.MeanAndStderr: MeanAndError(dims, bmp, lowQuality, population, rand, popLeft, popWidth, series.color, boxPos, useStdErr: true); break; case BoxStyle.MeanAndStdev: MeanAndError(dims, bmp, lowQuality, population, rand, popLeft, popWidth, series.color, boxPos, useStdErr: false); break; default: throw new NotImplementedException(); } } } }
public void Render(PlotDimensions dims, Bitmap bmp, bool lowQuality = false) { int numGroups = normalized.GetUpperBound(0) + 1; int numCategories = normalized.GetUpperBound(1) + 1; double sweepAngle = 2 * Math.PI / numCategories; double minScale = new double[] { dims.PxPerUnitX, dims.PxPerUnitX }.Min(); PointF origin = new PointF(dims.GetPixelX(0), dims.GetPixelY(0)); double[] radii = new double[] { 0.25 * minScale, 0.5 * minScale, 1 * minScale }; using (Graphics gfx = GDI.Graphics(bmp, lowQuality)) using (Pen pen = GDI.Pen(webColor)) using (Brush brush = GDI.Brush(Color.Black)) using (StringFormat sf = new StringFormat() { LineAlignment = StringAlignment.Center }) using (Font font = GDI.Font()) { for (int i = 0; i < radii.Length; i++) { gfx.DrawEllipse(pen, (int)(origin.X - radii[i]), (int)(origin.Y - radii[i]), (int)(radii[i] * 2), (int)(radii[i] * 2)); StringFormat stringFormat = new StringFormat() { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Far }; gfx.DrawString($"{normalizedMax * radii[i] / minScale:f1}", new Font(FontFamily.GenericSansSerif, 8), brush, origin.X, (float)(-radii[i] + origin.Y), stringFormat); } for (int i = 0; i < numCategories; i++) { PointF destination = new PointF((float)(1.1 * Math.Cos(sweepAngle * i - Math.PI / 2) * minScale + origin.X), (float)(1.1 * Math.Sin(sweepAngle * i - Math.PI / 2) * minScale + origin.Y)); gfx.DrawLine(pen, origin, destination); if (categoryNames != null) { PointF textDestination = new PointF( (float)(1.3 * Math.Cos(sweepAngle * i - Math.PI / 2) * minScale + origin.X), (float)(1.3 * Math.Sin(sweepAngle * i - Math.PI / 2) * minScale + origin.Y)); if (Math.Abs(textDestination.X - origin.X) < 0.1) { sf.Alignment = StringAlignment.Center; } else { sf.Alignment = dims.GetCoordinateX(textDestination.X) < 0 ? StringAlignment.Far : StringAlignment.Near; } gfx.DrawString(categoryNames[i], font, brush, textDestination, sf); } } for (int i = 0; i < numGroups; i++) { PointF[] points = new PointF[numCategories]; for (int j = 0; j < numCategories; j++) { points[j] = new PointF( (float)(normalized[i, j] * Math.Cos(sweepAngle * j - Math.PI / 2) * minScale + origin.X), (float)(normalized[i, j] * Math.Sin(sweepAngle * j - Math.PI / 2) * minScale + origin.Y)); } ((SolidBrush)brush).Color = fillColors[i]; pen.Color = lineColors[i]; gfx.FillPolygon(brush, points); gfx.DrawPolygon(pen, points); } } }
public void Render(PlotDimensions dims, Bitmap bmp, bool lowQuality = false) { using (Graphics gfx = GDI.Graphics(bmp, lowQuality)) using (Pen backgroundPen = GDI.Pen(dataBackgroundColor)) using (Pen outlinePen = GDI.Pen(outlineColor, outlineSize)) using (Brush brush = GDI.Brush(Color.Black)) using (Brush fontBrush = GDI.Brush(centerTextColor)) using (Font sliceFont = GDI.Font(null, sliceFontSize)) using (Font centerFont = GDI.Font(null, centerFontSize)) using (StringFormat sfCenter = new StringFormat() { LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Center }) { double[] proportions = values.Select(x => x / values.Sum()).ToArray(); AxisLimits2D limits = GetLimits(); double centreX = limits.xCenter; double centreY = limits.yCenter; float diameterPixels = .9f * Math.Min(dims.DataWidth, dims.DataHeight); // record label details and draw them after slices to prevent cover-ups double[] labelXs = new double[values.Length]; double[] labelYs = new double[values.Length]; string[] labelStrings = new string[values.Length]; RectangleF boundingRectangle = new RectangleF( dims.GetPixelX(centreX) - diameterPixels / 2, dims.GetPixelY(centreY) - diameterPixels / 2, diameterPixels, diameterPixels); if (donutSize > 0) { GraphicsPath graphicsPath = new GraphicsPath(); float donutDiameterPixels = (float)donutSize * diameterPixels; RectangleF donutHoleBoundingRectangle = new RectangleF( dims.GetPixelX(centreX) - donutDiameterPixels / 2, dims.GetPixelY(centreY) - donutDiameterPixels / 2, donutDiameterPixels, donutDiameterPixels); graphicsPath.AddEllipse(donutHoleBoundingRectangle); Region excludedRegion = new Region(graphicsPath); gfx.ExcludeClip(excludedRegion); } double start = -90; for (int i = 0; i < values.Length; i++) { // determine where the slice is to be drawn double sweep = proportions[i] * 360; double sweepOffset = explodedChart ? -1 : 0; double angle = (Math.PI / 180) * ((sweep + 2 * start) / 2); double xOffset = explodedChart ? 3 * Math.Cos(angle) : 0; double yOffset = explodedChart ? 3 * Math.Sin(angle) : 0; // record where and what to label the slice double sliceLabelR = 0.35 * diameterPixels; labelXs[i] = (boundingRectangle.X + diameterPixels / 2 + xOffset + Math.Cos(angle) * sliceLabelR); labelYs[i] = (boundingRectangle.Y + diameterPixels / 2 + yOffset + Math.Sin(angle) * sliceLabelR); string sliceLabelValue = (showValues) ? $"{values[i]}" : ""; string sliceLabelPercentage = showPercentages ? $"{proportions[i] * 100:f1}%" : ""; string sliceLabelName = (showLabels && groupNames != null) ? groupNames[i] : ""; labelStrings[i] = $"{sliceLabelValue}\n{sliceLabelPercentage}\n{sliceLabelName}".Trim(); ((SolidBrush)brush).Color = colors[i]; gfx.FillPie(brush: brush, x: (int)(boundingRectangle.X + xOffset), y: (int)(boundingRectangle.Y + yOffset), width: boundingRectangle.Width, height: boundingRectangle.Height, startAngle: (float)start, sweepAngle: (float)(sweep + sweepOffset)); if (explodedChart) { gfx.DrawPie( pen: backgroundPen, x: (int)(boundingRectangle.X + xOffset), y: (int)(boundingRectangle.Y + yOffset), width: boundingRectangle.Width, height: boundingRectangle.Height, startAngle: (float)start, sweepAngle: (float)(sweep + sweepOffset)); } start += sweep; } ((SolidBrush)brush).Color = Color.White; for (int i = 0; i < values.Length; i++) { if (!string.IsNullOrWhiteSpace(labelStrings[i])) { gfx.DrawString(labelStrings[i], sliceFont, brush, (float)labelXs[i], (float)labelYs[i], sfCenter); } } if (outlineSize > 0) { gfx.DrawEllipse( outlinePen, boundingRectangle.X, boundingRectangle.Y, boundingRectangle.Width, boundingRectangle.Height); } gfx.ResetClip(); if (centerText != null) { gfx.DrawString(centerText, centerFont, fontBrush, dims.GetPixelX(0), dims.GetPixelY(0), sfCenter); } if (explodedChart) { // draw a background-colored circle around the perimeter to make it look like all pieces are the same size backgroundPen.Width = 20; gfx.DrawEllipse( pen: backgroundPen, x: boundingRectangle.X, y: boundingRectangle.Y, width: boundingRectangle.Width, height: boundingRectangle.Height); } } }
public Pixel ToPixel(PlotDimensions dims) { return(dims.GetPixel(this)); }