void DrawScene(DrawingContext dc) { dc.DrawEllipse(new SolidColorBrush(Color.FromArgb(255, 200, 200, 200)), null, new Point(50, 18), 12, 12); dc.DrawEllipse(new SolidColorBrush(Color.FromArgb(255, 200, 200, 200)), new Pen(new SolidColorBrush(Color.FromArgb(255, 100, 100, 100)), 3), new Point(50, 51), 12, 12); dc.DrawEllipse(null, new Pen(new SolidColorBrush(Color.FromArgb(255, 100, 100, 100)), 3), new Point(50, 87), 12, 12); dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(255, 200, 200, 200)), null, new Rect(25, 111, 24, 24)); dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(255, 200, 200, 200)), new Pen(new SolidColorBrush(Color.FromArgb(255, 100, 100, 100)), 3), new Rect(25, 147, 24, 24)); dc.DrawRectangle(null, new Pen(new SolidColorBrush(Color.FromArgb(255, 100, 100, 100)), 3), new Rect(25, 184, 24, 24)); dc.DrawRoundedRectangle(new SolidColorBrush(Color.FromArgb(255, 200, 200, 200)), null, new Rect(25, 237, 24, 24), 5, 5); dc.DrawRoundedRectangle(new SolidColorBrush(Color.FromArgb(255, 200, 200, 200)), new Pen(new SolidColorBrush(Color.FromArgb(255, 100, 100, 100)), 3), new Rect(25, 270, 24, 24), 5, 5); dc.DrawRoundedRectangle(null, new Pen(new SolidColorBrush(Color.FromArgb(255, 100, 100, 100)), 3), new Rect(25, 307, 24, 24), 5, 5); dc.DrawLine(new Pen(new SolidColorBrush(Color.FromArgb(255, 100, 100, 100)), 3), new Point(50, 340), new Point (70, 360)); }
void drawLine_endBreak(DrawingContext dc, Pen drawingPen, Point line_p2, int range) { Point line_p3 = new Point(line_p2.X + range, line_p2.Y); dc.DrawLine(drawingPen, line_p2, line_p3); }
public void DrawLine(Float4 color, float thickness, Float2 a, Float2 b) => mContext.DrawLine(Pen(color, thickness), Point(a), Point(b));
public static void DrawLine(this DrawingContext drawingContext, Pen background, Pen foreground, Point start, Point end) { drawingContext.DrawLine(background, start, end); drawingContext.DrawLine(foreground, start, end); }
protected override void OnRender(DrawingContext dc) { if (Children.Count < 3 || Ticks < 0) { return; } var steps = Children.Count; var deltaAngle = 360D / steps; var center = new Point(RenderSize.Width / 2, RenderSize.Height / 2); var radius = Math.Min(RenderSize.Width, RenderSize.Height) / 2; //dc.DrawEllipse(null, pen, center, radius, radius); // Draw the background ticks between minRadius and maxRadius var minRadius = radius / 10; var maxRadius = radius * .8; var deltaRadius = (maxRadius - minRadius); var deltaTickRadius = deltaRadius / (Ticks - 1); var spokeLength = maxRadius + 10; for (var i = 0; i < Ticks; i++) { var curRadius = minRadius + i * deltaTickRadius; var angle = 0D; var p1 = GetPoint(center, curRadius, angle); for (var j = 0; j < steps; j++) { angle = (j + 1) * deltaAngle; var p2 = GetPoint(center, curRadius, angle); dc.DrawLine(DashedPen, p1, p2); p1 = p2; } // Draw the labels p1 = new Point(p1.X + 5, p1.Y - 15); if (i == 0) { dc.DrawText(new FormattedText(Minimum.ToString(CultureInfo.InvariantCulture), CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, LabelFont, 14, Brushes.Black), p1); } else if (i == Ticks - 1) { dc.DrawText(new FormattedText(Maximum.ToString(CultureInfo.InvariantCulture), CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, LabelFont, 14, Brushes.Black), p1); } } // Draw the spokes for (var i = 0; i < steps; i++) { var angle = i * deltaAngle; var p1 = GetPoint(center, spokeLength, angle); dc.DrawLine(Pen, center, p1); } // Draw the chart lines if (Lines == null) { return; } var scale = Maximum - Minimum; if (scale <= 0) { return; } foreach (var line in Lines) { var angle = 0D; var curRadius = minRadius + (line.PointDataSource[0] - Minimum) * deltaRadius / scale; var p1 = GetPoint(center, curRadius, angle); var myPathFigure = new PathFigure { StartPoint = p1, Segments = new PathSegmentCollection() }; var pts = new PointCollection(steps) { p1 }; for (var j = 1; j < steps; j++) { angle = (j) * deltaAngle; curRadius = minRadius + (line.PointDataSource[j] - Minimum) * deltaRadius / scale; var p2 = GetPoint(center, curRadius, angle); myPathFigure.Segments.Add(new LineSegment { Point = p2 }); pts.Add(p2); } myPathFigure.Segments.Add(new LineSegment { Point = p1 }); var myPathGeometry = new PathGeometry { Figures = new PathFigureCollection { myPathFigure } }; var pen = new Pen(new SolidColorBrush(line.LineColor), line.LineThickness); dc.DrawGeometry(line.FillColor == Colors.Transparent ? null : new SolidColorBrush(line.FillColor), pen, myPathGeometry); var brush = new SolidColorBrush(line.LineColor); // Draw fat circles on each data point foreach (var pt in pts) { dc.DrawEllipse(brush, pen, pt, line.LineThickness + 2, line.LineThickness + 2); } } }
public void Draw(TextView textView, DrawingContext drawingContext) { if (m_Markers == null || !textView.VisualLinesValid) { return; } var visualLines = textView.VisualLines; if (visualLines.Count == 0) { return; } int viewStart = visualLines.First().FirstDocumentLine.Offset; int viewEnd = visualLines.Last().LastDocumentLine.EndOffset; foreach (TextMarker marker in m_Markers.FindOverlappingSegments(viewStart, viewEnd - viewStart)) { if (marker.BackgroundColor != null) { BackgroundGeometryBuilder geoBuilder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; geoBuilder.AddSegment(textView, marker); Geometry geometry = geoBuilder.CreateGeometry(); if (geometry != null) { Color color = marker.BackgroundColor.Value; SolidColorBrush brush = new SolidColorBrush(color); brush.Freeze(); drawingContext.DrawGeometry(brush, null, geometry); } } var underlineMarkerTypes = TextMarkerTypes.SquigglyUnderline | TextMarkerTypes.NormalUnderline | TextMarkerTypes.DottedUnderline; if ((marker.MarkerTypes & underlineMarkerTypes) != 0) { foreach (Rect r in BackgroundGeometryBuilder.GetRectsForSegment(textView, marker)) { Point startPoint = r.BottomLeft; Point endPoint = r.BottomRight; Brush usedBrush = new SolidColorBrush(marker.MarkerColor); usedBrush.Freeze(); if ((marker.MarkerTypes & TextMarkerTypes.SquigglyUnderline) != 0) { double offset = 2.5; int count = Math.Max((int)((endPoint.X - startPoint.X) / offset) + 1, 4); StreamGeometry geometry = new StreamGeometry(); using (StreamGeometryContext ctx = geometry.Open()) { ctx.BeginFigure(startPoint, false, false); ctx.PolyLineTo(CreatePoints(startPoint, offset, count).ToArray(), true, false); } geometry.Freeze(); Pen usedPen = new Pen(usedBrush, 1); usedPen.Freeze(); drawingContext.DrawGeometry(Brushes.Transparent, usedPen, geometry); } if ((marker.MarkerTypes & TextMarkerTypes.NormalUnderline) != 0) { Pen usedPen = new Pen(usedBrush, 1); usedPen.Freeze(); drawingContext.DrawLine(usedPen, startPoint, endPoint); } if ((marker.MarkerTypes & TextMarkerTypes.DottedUnderline) != 0) { Pen usedPen = new Pen(usedBrush, 1) { DashStyle = DashStyles.Dot }; usedPen.Freeze(); drawingContext.DrawLine(usedPen, startPoint, endPoint); } } } } }
/// <summary> /// Draws a set of line graphs connecting the specified point collections to the /// specified <see cref="DrawingContext"/>.</summary> /// <param name="context"> /// The <see cref="DrawingContext"/> for the rendering.</param> /// <param name="bounds"> /// The region within <paramref name="context"/>, in device-independent pixels, where to /// draw.</param> /// <param name="colors"> /// An <see cref="Array"/> containing the <see cref="Color"/> for each graph.</param> /// <param name="points"> /// An <see cref="Array"/> containing the <see cref="Point"/> collections that /// constitute each graph.</param> /// <param name="typeface"> /// The <see cref="Typeface"/> to use for axis labels.</param> /// <exception cref="ArgumentException"> /// <paramref name="colors"/> and <paramref name="points"/> contain a different number /// of elements.</exception> /// <exception cref="ArgumentNullException"> /// <paramref name="context"/>, <paramref name="colors"/>, <paramref name="points"/>, or /// <paramref name="typeface"/> is a null reference.</exception> /// <remarks> /// <b>DrawGraph</b> does nothing if the specified <paramref name="points"/> array is /// empty, or contains only empty <see cref="Point"/> collections.</remarks> private static void DrawGraph(DrawingContext context, Rect bounds, Color[] colors, Point[][] points, Typeface typeface) { if (context == null) { ThrowHelper.ThrowArgumentNullException("context"); } if (colors == null) { ThrowHelper.ThrowArgumentNullException("colors"); } if (points == null) { ThrowHelper.ThrowArgumentNullException("values"); } if (typeface == null) { ThrowHelper.ThrowArgumentNullException("typeface"); } if (colors.Length != points.Length) { ThrowHelper.ThrowArgumentExceptionWithFormat( "colors", Tektosyne.Strings.ArgumentConflict, "points"); } // check for empty drawing region if (bounds.Width <= 0 || bounds.Height <= 0) { return; } Point minimum = new Point(Double.MaxValue, Double.MaxValue); Point maximum = new Point(Double.MinValue, Double.MinValue); // determine minimum and maximum coordinates foreach (Point[] line in points) { if (line == null) { continue; } foreach (Point point in line) { if (minimum.X > point.X) { minimum.X = point.X; } if (maximum.X < point.X) { maximum.X = point.X; } if (minimum.Y > point.Y) { minimum.Y = point.Y; } if (maximum.Y < point.Y) { maximum.Y = point.Y; } } } // check for empty point collections if (minimum.X > maximum.X || minimum.Y > maximum.Y) { return; } // ensure non-empty ranges along both axes if (minimum.X == maximum.X) { ++maximum.X; } if (minimum.Y == maximum.Y) { --minimum.Y; ++maximum.Y; } // determine horizontal and vertical scale double scaleX = bounds.Width / (maximum.X - minimum.X); double scaleY = bounds.Height / (maximum.Y - minimum.Y); // determine horizontal and vertical origin Point origin = new Point( bounds.Left - scaleX * minimum.X, bounds.Top + scaleY * maximum.Y); // create required pens Pen blackPen = new Pen(Brushes.Black, 1.0); Pen lightPen = new Pen(Brushes.LightGray, 1.0); // draw black lines of origin context.DrawLine(blackPen, new Point(origin.X, bounds.Top), new Point(origin.X, bounds.Bottom)); context.DrawLine(blackPen, new Point(bounds.Left, origin.Y), new Point(bounds.Right, origin.Y)); // calculate optimal axis divisions Point division = new Point( GetAxisDivision(maximum.X - minimum.X), GetAxisDivision(maximum.Y - minimum.Y)); // draw vertical tick lines and labels for (double tick = (maximum.X / division.X) * division.X; tick >= minimum.X; tick -= division.X) { // draw division line double x = origin.X + tick * scaleX; context.DrawLine(lightPen, new Point(x, bounds.Top), new Point(x, bounds.Bottom)); // print label left of line string tickText = tick.ToString("N0", ApplicationInfo.Culture); var text = new FormattedText(tickText, ApplicationInfo.Culture, FlowDirection.LeftToRight, typeface, 10, Brushes.Black); context.DrawText(text, new Point(x - 12, bounds.Top + 2)); } // draw horizontal tick lines and labels for (double tick = (maximum.Y / division.Y) * division.Y; tick >= minimum.Y; tick -= division.Y) { // draw division line double y = origin.Y - Fortran.NInt(tick * scaleY); context.DrawLine(lightPen, new Point(bounds.Left, y), new Point(bounds.Right, y)); // print label below line string tickText = tick.ToString("N0", ApplicationInfo.Culture); var text = new FormattedText(tickText, ApplicationInfo.Culture, FlowDirection.LeftToRight, typeface, 10, Brushes.Black); context.DrawText(text, new Point(bounds.Left + 4, y + 2)); } // draw all point collections for (int i = 0; i < points.Length; i++) { Point[] line = points[i]; if (line == null) { continue; } // draw lines from one point to the next Pen pen = new Pen(new SolidColorBrush(colors[i]), 2.0); for (int j = 0; j < line.Length - 1; j++) { Point p0 = new Point(origin.X + line[j].X * scaleX, origin.Y - line[j].Y * scaleY); Point p1 = new Point(origin.X + line[j + 1].X * scaleX, origin.Y - line[j + 1].Y * scaleY); context.DrawLine(pen, p0, p1); } } }
protected override void OnRender(DrawingContext dc, double renderWidth) { // This may be true if the UI for a column hasn't been loaded yet (e.g., restoring multiple tabs from workspace won't load each tab until it's clicked by the user) if (gridPen == null) { if (UiWrapper != null && PresentationSource.FromVisual(UiWrapper) != null) { Matrix m = PresentationSource.FromVisual(UiWrapper).CompositionTarget.TransformToDevice; double dpiFactor = 1 / m.M11; gridPen = new Pen(Application.Current.TryFindResource("BorderThinBrush") as Brush, 1 * dpiFactor); halfPenWidth = gridPen.Thickness * 0.5; } } double verticalOffset = -gridPen.Thickness; lock (SuperDom.Rows) foreach (PriceRow row in SuperDom.Rows) { if (renderWidth - halfPenWidth >= 0) { // Draw a cell Rect rect = new Rect(-halfPenWidth, verticalOffset, renderWidth - halfPenWidth, SuperDom.ActualRowHeight); // Create a guidelines set GuidelineSet guidelines = new GuidelineSet(); guidelines.GuidelinesX.Add(rect.Left + halfPenWidth); guidelines.GuidelinesX.Add(rect.Right + halfPenWidth); guidelines.GuidelinesY.Add(rect.Top + halfPenWidth); guidelines.GuidelinesY.Add(rect.Bottom + halfPenWidth); dc.PushGuidelineSet(guidelines); if (SuperDom.IsConnected && SuperDom.Position != null && SuperDom.Position.MarketPosition != Cbi.MarketPosition.Flat) { double pnL = SuperDom.Position.GetUnrealizedProfitLoss(PnlDisplayUnit, row.Price); string pnlString = string.Empty; switch (PnlDisplayUnit) { case Cbi.PerformanceUnit.Currency: pnlString = Core.Globals.FormatCurrency(pnL, SuperDom.Position); break; case Cbi.PerformanceUnit.Percent: pnlString = pnL.ToString("P", Core.Globals.GeneralOptions.CurrentCulture); break; case Cbi.PerformanceUnit.Pips: pnlString = (Math.Round(pnL * 10) / 10.0).ToString("0.0", forexCulture); break; case Cbi.PerformanceUnit.Points: pnlString = SuperDom.Position.Instrument.MasterInstrument.RoundToTickSize(pnL).ToString("0.#######", Core.Globals.GeneralOptions.CurrentCulture); break; case Cbi.PerformanceUnit.Ticks: pnlString = Math.Round(pnL).ToString(Core.Globals.GeneralOptions.CurrentCulture); break; } dc.DrawRectangle(pnL > 0 ? PositiveBackColor : NegativeBackColor, null, rect); dc.DrawLine(gridPen, new Point(-gridPen.Thickness, rect.Bottom), new Point(renderWidth - halfPenWidth, rect.Bottom)); dc.DrawLine(gridPen, new Point(rect.Right, verticalOffset), new Point(rect.Right, rect.Bottom)); // Print PnL value - remember to set MaxTextWidth so text doesn't spill into another column fontFamily = SuperDom.Font.Family; typeFace = new Typeface(fontFamily, SuperDom.Font.Italic ? FontStyles.Italic : FontStyles.Normal, SuperDom.Font.Bold ? FontWeights.Bold : FontWeights.Normal, FontStretches.Normal); if (renderWidth - 6 > 0) { FormattedText pnlText = new FormattedText(pnlString, Core.Globals.GeneralOptions.CurrentCulture, FlowDirection.LeftToRight, typeFace, SuperDom.Font.Size, SuperDom.Position.Instrument.MasterInstrument.RoundToTickSize(pnL) > 0 ? PositiveForeColor : NegativeForeColor) { MaxLineCount = 1, MaxTextWidth = renderWidth - 6, Trimming = TextTrimming.CharacterEllipsis }; dc.DrawText(pnlText, new Point(4, verticalOffset + (SuperDom.ActualRowHeight - pnlText.Height) / 2)); } } else { dc.DrawRectangle(BackColor, null, rect); dc.DrawLine(gridPen, new Point(-gridPen.Thickness, rect.Bottom), new Point(renderWidth - halfPenWidth, rect.Bottom)); dc.DrawLine(gridPen, new Point(rect.Right, verticalOffset), new Point(rect.Right, rect.Bottom)); } dc.Pop(); verticalOffset += SuperDom.ActualRowHeight; } } }
public override void DrawEquation(DrawingContext dc) { base.DrawEquation(dc); dc.DrawLine(StandardPen, new Point(bottomEquation.Left - ExtraWidth / 10, Top), new Point(topEquation.Right + ExtraWidth / 10, Bottom)); }
/// <summary> /// Custom StrokeEraser Drawing /// </summary> /// <returns></returns> private static Drawing CreateStrokeEraserDrawing() { DrawingGroup drawingGroup = new DrawingGroup(); DrawingContext dc = null; try { dc = drawingGroup.Open(); LinearGradientBrush brush1 = new LinearGradientBrush( Color.FromRgb(240, 242, 255), // Start Color Color.FromRgb(180, 207, 248), // End Color 45f // Angle ); brush1.Freeze(); SolidColorBrush brush2 = new SolidColorBrush(Color.FromRgb(180, 207, 248)); brush2.Freeze(); Pen pen1 = new Pen(Brushes.Gray, 0.7); pen1.Freeze(); PathGeometry pathGeometry = new PathGeometry(); PathFigure path = new PathFigure(); path.StartPoint = new Point(5, 5); LineSegment segment = new LineSegment(new Point(16, 5), true); segment.Freeze(); path.Segments.Add(segment); segment = new LineSegment(new Point(26, 15), true); segment.Freeze(); path.Segments.Add(segment); segment = new LineSegment(new Point(15, 15), true); segment.Freeze(); path.Segments.Add(segment); segment = new LineSegment(new Point(5, 5), true); segment.Freeze(); path.Segments.Add(segment); path.IsClosed = true; path.Freeze(); pathGeometry.Figures.Add(path); path = new PathFigure(); path.StartPoint = new Point(5, 5); segment = new LineSegment(new Point(5, 10), true); segment.Freeze(); path.Segments.Add(segment); segment = new LineSegment(new Point(15, 19), true); segment.Freeze(); path.Segments.Add(segment); segment = new LineSegment(new Point(15, 15), true); segment.Freeze(); path.Segments.Add(segment); segment = new LineSegment(new Point(5, 5), true); segment.Freeze(); path.Segments.Add(segment); path.IsClosed = true; path.Freeze(); pathGeometry.Figures.Add(path); pathGeometry.Freeze(); PathGeometry pathGeometry1 = new PathGeometry(); path = new PathFigure(); path.StartPoint = new Point(15, 15); segment = new LineSegment(new Point(15, 19), true); segment.Freeze(); path.Segments.Add(segment); segment = new LineSegment(new Point(26, 19), true); segment.Freeze(); path.Segments.Add(segment); segment = new LineSegment(new Point(26, 15), true); segment.Freeze(); path.Segments.Add(segment); segment.Freeze(); segment = new LineSegment(new Point(15, 15), true); path.Segments.Add(segment); path.IsClosed = true; path.Freeze(); pathGeometry1.Figures.Add(path); pathGeometry1.Freeze(); dc.DrawGeometry(brush1, pen1, pathGeometry); dc.DrawGeometry(brush2, pen1, pathGeometry1); dc.DrawLine(pen1, new Point(5, 5), new Point(5, 0)); dc.DrawLine(pen1, new Point(5, 5), new Point(0, 5)); dc.DrawLine(pen1, new Point(5, 5), new Point(2, 2)); dc.DrawLine(pen1, new Point(5, 5), new Point(8, 2)); dc.DrawLine(pen1, new Point(5, 5), new Point(2, 8)); } finally { if (dc != null) { dc.Close(); } } return(drawingGroup); }
/// <summary> /// Draws a line form left to right margin at specified y-postion. /// </summary> void DrawLine(DrawingContext ctx, double yPos, double thickness) { ctx.DrawLine(new Pen(new SolidColorBrush(Colors.Black), thickness), new Point(m_Margins.Left, yPos), new Point(m_PageSize.Width - m_Margins.Right, yPos)); }
private void UpdateTexture() { Application.Current.Dispatcher.Invoke( new Action( delegate() { bool showUlna = (m_settings != null && m_settings.ShowUlna); bool showGuides = (m_settings != null && m_settings.ShowGuides); int textureWidth = 1024; int textureHeight = 1024; DrawingVisual visual = new DrawingVisual(); DrawingContext context = visual.RenderOpen(); context.DrawRectangle(new SolidColorBrush(Constants.Colors.SkinTextureColor), null, new Rect(0.0, 0.0, textureWidth, textureHeight)); // draw the guides double lineThickness = 10.0; for (int i = 0; i <= 4; i++) { Pen dashedPen = new Pen(Brushes.DarkGray, lineThickness / 4.0); DashStyle dashStyle = new DashStyle(new double[] { 4.0, 8.0 }, 0.0); if (i % 4 == 0 && showUlna) { dashedPen.Brush = Brushes.DarkRed; } else { dashedPen.DashStyle = dashStyle; } if ((i % 4 == 0 && showUlna) || (i % 4 != 0 && showGuides)) { context.DrawLine(dashedPen, new Point(0.0, i / 4.0 * textureHeight + 0.0 * textureHeight), new Point(textureWidth, i / 4.0 * textureHeight + 0.0 * textureHeight)); context.DrawLine(dashedPen, new Point(0.0, i / 4.0 * textureHeight + 0.0 * textureHeight - textureHeight), new Point(textureWidth, i / 4.0 * textureHeight + 0.0 * textureHeight - textureHeight)); context.DrawLine(dashedPen, new Point(0.0, i / 4.0 * textureHeight + 0.0 * textureHeight + textureHeight), new Point(textureWidth, i / 4.0 * textureHeight + 0.0 * textureHeight + textureHeight)); } } // let's draw the grid if (m_grids != null) { bool[] showModels = new bool[3]; showModels[0] = (m_settings != null && m_settings.ShowHorizontalModel); showModels[1] = (m_settings != null && m_settings.ShowVerticalModel); showModels[2] = (m_settings != null && m_settings.ShowTracingModel); int counter = 0; foreach (Tuple <Brush, Point[, ]> grid in m_grids) { if (showModels[counter % 3]) { Pen linePen = new Pen(grid.Item1, 7.5); linePen.DashCap = PenLineCap.Round; int rows = grid.Item2.GetLength(0); int cols = grid.Item2.GetLength(1); // get the four edges List <Tuple <Point, Point> > edges = new List <Tuple <Point, Point> >(); edges.Add(new Tuple <Point, Point>(grid.Item2[0, 0], grid.Item2[0, cols - 1])); edges.Add(new Tuple <Point, Point>(grid.Item2[0, cols - 1], grid.Item2[rows - 1, cols - 1])); edges.Add(new Tuple <Point, Point>(grid.Item2[rows - 1, cols - 1], grid.Item2[rows - 1, 0])); edges.Add(new Tuple <Point, Point>(grid.Item2[rows - 1, 0], grid.Item2[0, 0])); List <Point> polygonPts = new List <Point>(); foreach (Tuple <Point, Point> edge in edges) { Point correctPt = new Point(edge.Item1.X * textureWidth, edge.Item1.Y * textureHeight); polygonPts.Add(correctPt); } PathFigure polygonFigure = new PathFigure(); polygonFigure.StartPoint = polygonPts[0]; polygonFigure.Segments.Add(new LineSegment(polygonPts[1], true)); polygonFigure.Segments.Add(new LineSegment(polygonPts[2], true)); polygonFigure.Segments.Add(new LineSegment(polygonPts[3], true)); polygonFigure.Segments.Add(new LineSegment(polygonPts[0], true)); polygonFigure.IsClosed = true; PathGeometry polygon = new PathGeometry(); polygon.Figures.Add(polygonFigure); context.DrawGeometry(new SolidColorBrush( Color.FromArgb(32, ((SolidColorBrush)grid.Item1).Color.R, ((SolidColorBrush)grid.Item1).Color.G, ((SolidColorBrush)grid.Item1).Color.B)), linePen, polygon); // add the grid lines Pen gridPen = new Pen(grid.Item1, 4.0); gridPen.DashCap = PenLineCap.Round; DashStyle dashStyle = new DashStyle(new double[] { 2.0, 4.0 }, 0.0); gridPen.DashStyle = dashStyle; // horizontal first for (int i = 1; i < cols - 1; i++) { Point startPt = new Point(grid.Item2[0, i].X * textureWidth, grid.Item2[0, i].Y * textureHeight); Point endPt = new Point(grid.Item2[rows - 1, i].X * textureWidth, grid.Item2[rows - 1, i].Y * textureHeight); context.DrawLine(gridPen, startPt, endPt); } // now vertical for (int i = 1; i < rows - 1; i++) { Point startPt = new Point(grid.Item2[i, 0].X * textureWidth, grid.Item2[i, 0].Y * textureHeight); Point endPt = new Point(grid.Item2[i, cols - 1].X * textureWidth, grid.Item2[i, cols - 1].Y * textureHeight); context.DrawLine(gridPen, startPt, endPt); } } counter++; } } if (m_projectedPoint != null) { double size = 30.0; Point correctPoint = new Point(m_projectedPoint.Item2.X * textureWidth, m_projectedPoint.Item2.Y * textureHeight); Brush pointBrush = new SolidColorBrush(Color.FromArgb( 128, ((SolidColorBrush)m_projectedPoint.Item1).Color.R, ((SolidColorBrush)m_projectedPoint.Item1).Color.G, ((SolidColorBrush)m_projectedPoint.Item1).Color.B)); Pen pointPen = new Pen(m_projectedPoint.Item1, 5.0); context.DrawEllipse(pointBrush, pointPen, correctPoint, size / 2.0, size / 2.0); } context.Close(); m_texture = new RenderTargetBitmap( textureWidth, textureHeight, 96.0, 96.0, PixelFormats.Pbgra32); ((RenderTargetBitmap)m_texture).Render(visual); m_outsideMaterial = new DiffuseMaterial(new ImageBrush(m_texture)); m_armModel.Material = m_outsideMaterial; })); }
private ImageSource CreateGenericTexture(bool colored = false) { bool showUlna = (m_settings != null && m_settings.ShowUlna); bool showGuides = (m_settings != null && m_settings.ShowGuides); int textureWidth = 1024; int textureHeight = 1024; DrawingVisual visual = new DrawingVisual(); DrawingContext context = visual.RenderOpen(); context.DrawRectangle(new SolidColorBrush(Constants.Colors.SkinTextureColor), null, new Rect(0.0, 0.0, textureWidth, textureHeight)); double lineThickness = 10.0; for (int i = 0; i <= 4; i++) { Pen dashedPen = new Pen(Brushes.DarkGray, lineThickness / 2.0); DashStyle dashStyle = new DashStyle(new double[] { 4.0, 8.0 }, 0.0); if (i % 4 == 0 && m_settings.ShowUlna) { dashedPen.Brush = Brushes.DarkRed; } else { dashedPen.DashStyle = dashStyle; } if (colored) { switch (i) { default: case 0: dashedPen.Brush = Brushes.Red; break; case 1: dashedPen.Brush = Brushes.Green; break; case 2: dashedPen.Brush = Brushes.Blue; break; case 3: dashedPen.Brush = Brushes.Yellow; break; } } if ((i % 4 == 0 && showUlna) || (i % 4 != 0 && showGuides)) { context.DrawLine(dashedPen, new Point(0.0, i / 4.0 * textureHeight + 0.0 * textureHeight), new Point(textureWidth, i / 4.0 * textureHeight + 0.0 * textureHeight)); context.DrawLine(dashedPen, new Point(0.0, i / 4.0 * textureHeight + 0.0 * textureHeight - textureHeight), new Point(textureWidth, i / 4.0 * textureHeight + 0.0 * textureHeight - textureHeight)); context.DrawLine(dashedPen, new Point(0.0, i / 4.0 * textureHeight + 0.0 * textureHeight + textureHeight), new Point(textureWidth, i / 4.0 * textureHeight + 0.0 * textureHeight + textureHeight)); } } context.Close(); RenderTargetBitmap bitmap = new RenderTargetBitmap( textureWidth, textureHeight, 96.0, 96.0, PixelFormats.Pbgra32); bitmap.Render(visual); return(bitmap); }
protected override void OnRender(DrawingContext drawingContext) { var itemsControl = this.DropInfo.VisualTarget as ItemsControl; if (itemsControl != null) { // Get the position of the item at the insertion index. If the insertion point is // to be after the last item, then get the position of the last item and add an // offset later to draw it at the end of the list. ItemsControl itemParent; if (this.DropInfo.VisualTargetItem != null) { itemParent = ItemsControl.ItemsControlFromItemContainer(this.DropInfo.VisualTargetItem); } else { itemParent = itemsControl; } var index = Math.Min(this.DropInfo.InsertIndex, itemParent.Items.Count - 1); var lastItemInGroup = false; var targetGroup = this.DropInfo.TargetGroup; if (targetGroup != null && targetGroup.IsBottomLevel && this.DropInfo.InsertPosition.HasFlag(RelativeInsertPosition.AfterTargetItem)) { var indexOf = targetGroup.Items.IndexOf(this.DropInfo.TargetItem); lastItemInGroup = indexOf == targetGroup.ItemCount - 1; if (lastItemInGroup && this.DropInfo.InsertIndex != itemParent.Items.Count) { index--; } } var itemContainer = (UIElement)itemParent.ItemContainerGenerator.ContainerFromIndex(index); if (itemContainer != null) { var itemRect = new Rect(itemContainer.TranslatePoint(new Point(), this.AdornedElement), itemContainer.RenderSize); Point point1, point2; double rotation = 0; if (this.DropInfo.VisualTargetOrientation == Orientation.Vertical) { if (this.DropInfo.InsertIndex == itemParent.Items.Count || lastItemInGroup) { itemRect.Y += itemContainer.RenderSize.Height; } point1 = new Point(itemRect.X, itemRect.Y); point2 = new Point(itemRect.Right, itemRect.Y); } else { var itemRectX = itemRect.X; if (this.DropInfo.VisualTargetFlowDirection == FlowDirection.LeftToRight && this.DropInfo.InsertIndex == itemParent.Items.Count) { itemRectX += itemContainer.RenderSize.Width; } else if (this.DropInfo.VisualTargetFlowDirection == FlowDirection.RightToLeft && this.DropInfo.InsertIndex != itemParent.Items.Count) { itemRectX += itemContainer.RenderSize.Width; } point1 = new Point(itemRectX, itemRect.Y); point2 = new Point(itemRectX, itemRect.Bottom); rotation = 90; } drawingContext.DrawLine(m_Pen, point1, point2); this.DrawTriangle(drawingContext, point1, rotation); this.DrawTriangle(drawingContext, point2, 180 + rotation); } } }
protected void Paint(DrawingContext dc, SignalTrack track, Signal signal, int dimension, double height, uint width, bool isAudio) { if (signal.number == 0 || signal.data == null || height == 0 || width == 0) { return; } if (isAudio) { for (int d = dimension; d <= dimension; d++) { float zoomFactor = track.zoomLevel * ((signal.max[d] - signal.min[d]) / 10); float zoomOffset = track.zoomOffset * ((signal.max[d] - signal.min[d]) / 10); float minVal = signal.min[d] + zoomFactor; float maxVal = signal.max[d] - zoomFactor; float offset = minVal; float scale = (float)height / (maxVal - offset); offset += zoomOffset; Point from = new Point(); Point to = new Point(); if (width == signal.number) { for (int i = 0; i < signal.number; i++) { from.X = to.X = i; from.Y = height - (signal.data[i * signal.dim + d] - offset) * scale; to.Y = height - (-signal.data[i * signal.dim + d] - offset) * scale; if (to.Y > height) { to.Y = height; } else if (to.Y < 0) { to.Y = 0; } dc.DrawLine(pen, from, to); } } else { float step = (float)width / (float)signal.number; for (int i = 0; i < signal.number; i++) { from.X = to.X = (uint)i * step; from.Y = height - (signal.data[i * signal.dim + d] - offset) * scale; to.Y = height - (-signal.data[i * signal.dim + d] - offset) * scale; if (to.Y > height) { to.Y = height; } else if (to.Y < 0) { to.Y = 0; } dc.DrawLine(pen, from, to); } } } } else { if (signal.type == Signal.Type.CHAR) { for (int d = dimension; d <= dimension; d++) { float zoomFactor = track.zoomLevel * ((signal.max[d] - signal.min[d]) / 10); float zoomOffset = track.zoomOffset * ((signal.max[d] - signal.min[d]) / 10); float minVal = signal.min[d] + zoomFactor; float maxVal = signal.max[d] - zoomFactor; float offset = minVal; float scale = (float)height / (maxVal - offset); offset += zoomOffset; Point from = new Point(0, height - (signal.data[d] - offset) * scale); Point to = new Point(); float step = (float)width / (float)signal.number; for (int i = 0; i < signal.number; i++) { to.X = (uint)i * step; to.Y = height - (signal.data[i * signal.dim + d] - offset) * scale; if (to.Y > height) { to.Y = height; } else if (to.Y < 0) { to.Y = 0; } dc.DrawLine(pen, from, to); from.X = to.X; from.Y = to.Y; } } } else { for (int d = dimension; d <= dimension; d++) { float zoomFactor = track.zoomLevel * ((signal.max[d] - signal.min[d]) / 10); float zoomOffset = track.zoomOffset * ((signal.max[d] - signal.min[d]) / 10); float minVal = signal.min[d] + zoomFactor; float maxVal = signal.max[d] - zoomFactor; float offset = minVal; float scale = (float)height / (maxVal - offset); offset += zoomOffset; Point from = new Point(0, height - (signal.data[d] - offset) * scale); Point to = new Point(); if (width == signal.number) { for (int i = 0; i < signal.number; i++) { to.X = i; to.Y = height - (signal.data[i * signal.dim + d] - offset) * scale; if (to.Y > height) { to.Y = height; } else if (to.Y < 0) { to.Y = 0; } dc.DrawLine(pen, from, to); from.X = to.X; from.Y = to.Y; } } else { float step = (float)width / (float)signal.number; for (int i = 0; i < signal.number; i++) { to.X = (uint)i * step; to.Y = height - (signal.data[i * signal.dim + d] - offset) * scale; if (to.Y > height) { to.Y = height; } else if (to.Y < 0) { to.Y = 0; } dc.DrawLine(pen, from, to); from.X = to.X; from.Y = to.Y; } } } } } }
public void Draw(TextView textView, DrawingContext drawingContext) { var xPos = textView.TextSurfaceBounds.X + textView.CharSize.Width*120.0; drawingContext.DrawLine(new Pen(brush, 1), new Point(xPos, 0), new Point(xPos, textView.Bounds.Bottom)); }
public override DocumentPage GetPage(int pageNumber) { if (_typePrinting) { FormattedText text = GetFormattedText("A"); double col1_X = _margin; double col2_X = col1_X + text.Width * 5; double col3_X = col1_X + text.Width * 30; double col4_X = col1_X + text.Width * 50; int minRow = pageNumber * _rowsPerPage; int maxRow = minRow + _rowsPerPage; // Создать визуальный элемент для страницы DrawingVisual visual = new DrawingVisual(); // Установить позицию в верхний левый угол печатаемой области Point point = new Point(_margin, _margin); using (DrawingContext dc = visual.RenderOpen()) { // Нарисовать заголовки столбцов Typeface columnHeaderTypeface = new Typeface(_typeFace.FontFamily, FontStyles.Normal, FontWeights.Bold, FontStretches.Normal); point.X = col1_X; text = GetFormattedText("Id", columnHeaderTypeface); dc.DrawText(text, point); text = GetFormattedText("Фамилия", columnHeaderTypeface); point.X = col2_X; dc.DrawText(text, point); text = GetFormattedText("Имя", columnHeaderTypeface); point.X = col3_X; dc.DrawText(text, point); text = GetFormattedText("Отчество", columnHeaderTypeface); point.X = col4_X; dc.DrawText(text, point); // Нарисовать линию подчеркивания dc.DrawLine(new Pen(Brushes.Black, 2), new Point(_margin, _margin + text.Height), new Point(_size.Width - _margin, _margin + text.Height)); point.Y += text.Height; // Нарисовать значения столбцов for (int i = minRow; i < maxRow; i++) { // Проверить конец последней (частично заполненной) страницы if (i > (_table.Rows.Count - 1)) { break; } point.X = col1_X; text = GetFormattedText(_table.Rows[i]["Id"].ToString()); dc.DrawText(text, point); // Добавить второй столбец text = GetFormattedText(_table.Rows[i]["FirstSurname"].ToString()); point.X = col2_X; dc.DrawText(text, point); text = GetFormattedText(_table.Rows[i]["Name"].ToString()); point.X = col3_X; dc.DrawText(text, point); text = GetFormattedText(_table.Rows[i]["Patronymic"].ToString()); point.X = col4_X; dc.DrawText(text, point); point.Y += text.Height; } } return(new DocumentPage(visual, _size, new Rect(_size), new Rect(_size))); } else { FormattedText text = GetFormattedText("A"); double col1_X = _margin; string textRow; int minRow = pageNumber * _rowsPerPage; int maxRow = minRow + _rowsPerPage; // Создать визуальный элемент для страницы DrawingVisual visual = new DrawingVisual(); // Установить позицию в верхний левый угол печатаемой области Point point = new Point(_margin, _margin); using (DrawingContext dc = visual.RenderOpen()) { // Нарисовать заголовки столбцов Typeface columnHeaderTypeface = new Typeface(_typeFace.FontFamily, FontStyles.Normal, FontWeights.Bold, FontStretches.Normal); point.X = col1_X; text = GetFormattedText("Информация о работнике", columnHeaderTypeface); dc.DrawText(text, point); dc.DrawText(text, point); // Нарисовать линию подчеркивания dc.DrawLine(new Pen(Brushes.Black, 2), new Point(_margin, _margin + text.Height), new Point(_size.Width - _margin, _margin + text.Height)); point.Y += text.Height; // Нарисовать значения столбцов for (int i = minRow; i < maxRow; i++) { // Проверить конец последней (частично заполненной) страницы if (i > (_table.Rows.Count - 1)) { break; } point.X = col1_X; textRow = _table.Rows[i]["Id"].ToString(); if (!String.IsNullOrEmpty(textRow)) { text = GetFormattedText("Id - " + textRow); dc.DrawText(text, point); point.Y += text.Height; } // Добавить вторую строку textRow = _table.Rows[i]["FirstSurname"].ToString(); if (!String.IsNullOrEmpty(textRow)) { text = GetFormattedText("Первая фамилия - " + textRow); dc.DrawText(text, point); point.Y += text.Height; } textRow = _table.Rows[i]["SecondSurname"].ToString(); if (!String.IsNullOrEmpty(textRow)) { text = GetFormattedText("Вторая фамилия - " + textRow); dc.DrawText(text, point); point.Y += text.Height; } textRow = _table.Rows[i]["ThirdSurname"].ToString(); if (!String.IsNullOrEmpty(textRow)) { text = GetFormattedText("Третья фамилия - " + textRow); dc.DrawText(text, point); point.Y += text.Height; } textRow = _table.Rows[i]["Name"].ToString(); if (!String.IsNullOrEmpty(textRow)) { text = GetFormattedText("Имя - " + textRow); dc.DrawText(text, point); point.Y += text.Height; } textRow = _table.Rows[i]["Patronymic"].ToString(); if (!String.IsNullOrEmpty(textRow)) { text = GetFormattedText("Отчество - " + textRow); dc.DrawText(text, point); point.Y += text.Height; } textRow = _table.Rows[i]["PassportInfo"].ToString(); if (!String.IsNullOrEmpty(textRow)) { text = GetFormattedText("Паспортные данные - " + textRow); dc.DrawText(text, point); point.Y += text.Height; } textRow = _table.Rows[i]["Registration"].ToString(); if (!String.IsNullOrEmpty(textRow)) { text = GetFormattedText("Прописка - " + textRow); dc.DrawText(text, point); point.Y += text.Height; } textRow = _table.Rows[i]["RegistrationNumber"].ToString(); if (!String.IsNullOrEmpty(textRow)) { text = GetFormattedText("Инн - " + textRow); dc.DrawText(text, point); point.Y += text.Height; } textRow = _table.Rows[i]["Phone"].ToString(); if (!String.IsNullOrEmpty(textRow)) { text = GetFormattedText("Телефон - " + textRow); dc.DrawText(text, point); point.Y += text.Height; } textRow = _table.Rows[i]["FirstPosition"].ToString(); if (!String.IsNullOrEmpty(textRow)) { text = GetFormattedText("Первая должность - " + textRow); dc.DrawText(text, point); point.Y += text.Height; } textRow = _table.Rows[i]["SecondPosition"].ToString(); if (!String.IsNullOrEmpty(textRow)) { text = GetFormattedText("Вторая должность - " + textRow); dc.DrawText(text, point); point.Y += text.Height; } textRow = _table.Rows[i]["ThirdPosition"].ToString(); if (!String.IsNullOrEmpty(textRow)) { text = GetFormattedText("Третья должность - " + textRow); dc.DrawText(text, point); point.Y += text.Height; } textRow = _table.Rows[i]["FirstOrder"].ToString(); if (!String.IsNullOrEmpty(textRow)) { text = GetFormattedText("Первый приказ - " + textRow); dc.DrawText(text, point); point.Y += text.Height; } textRow = _table.Rows[i]["SecondOrder"].ToString(); if (!String.IsNullOrEmpty(textRow)) { text = GetFormattedText("Второй приказ - " + textRow); dc.DrawText(text, point); point.Y += text.Height; } textRow = _table.Rows[i]["Additionally"].ToString(); if (!String.IsNullOrEmpty(textRow)) { text = GetFormattedText("Дополнительно - " + textRow); dc.DrawText(text, point); point.Y += text.Height; } if (DateTime.TryParse(_table.Rows[i]["DateOfDismissal"].ToString(), out DateTime dod)) { textRow = dod.ToShortDateString(); text = GetFormattedText("Дата увольнения - " + textRow); dc.DrawText(text, point); point.Y += text.Height; } textRow = Convert.ToDateTime(_table.Rows[i]["EmploymentDate"]).ToShortDateString(); if (!String.IsNullOrEmpty(textRow)) { text = GetFormattedText("Дата приема на работу - " + textRow); dc.DrawText(text, point); point.Y += text.Height; } textRow = Convert.ToDateTime(_table.Rows[i]["DateOfBirth"]).ToShortDateString(); if (!String.IsNullOrEmpty(textRow)) { text = GetFormattedText("Дата рождения - " + textRow); dc.DrawText(text, point); point.Y += text.Height; } textRow = _table.Rows[i]["WorkDays"].ToString(); if (!String.IsNullOrEmpty(textRow)) { text = GetFormattedText("Дни работы - " + textRow); dc.DrawText(text, point); } } } return(new DocumentPage(visual, _size, new Rect(_size), new Rect(_size))); } }
/// <summary> /// sets the tick values /// </summary> /// <param name="dc"></param> public override void Render(DrawingContext dc) { if (DoubleUtil.IsDoubleFinite(Width) == false) { this.Width = controlSize.Width; //base.Render(dc); //return; } Size size = new Size(Width, Height); double range = Maximum - Minimum; double tickLen = 0.0d; // Height for Primary Tick (for Mininum and Maximum value) double tickLen2; // Height for Secondary Tick double logicalToPhysical = 1.0; double progression = 1.0d; Point startPoint = new Point(0d, 0d); Point endPoint = new Point(0d, 0d); // Take Thumb size in to account double halfReservedSpace = ReservedSpace * 0.5; switch (Placement) { case TickBarPlacement.Top: if (DoubleUtil.GreaterThanOrClose(ReservedSpace, size.Width)) { return; } size = new Size(size.Width - ReservedSpace, size.Height); tickLen = -size.Height; startPoint = new Point(halfReservedSpace, size.Height); endPoint = new Point(halfReservedSpace + size.Width, size.Height); logicalToPhysical = size.Width / range; progression = 1; break; case TickBarPlacement.Bottom: if (DoubleUtil.GreaterThanOrClose(ReservedSpace, size.Width)) { return; } size = new Size(size.Width - ReservedSpace, size.Height); tickLen = size.Height; startPoint = new Point(halfReservedSpace, 0d); endPoint = new Point(halfReservedSpace + size.Width, 0d); logicalToPhysical = size.Width / range; progression = 1; break; case TickBarPlacement.Left: if (DoubleUtil.GreaterThanOrClose(ReservedSpace, size.Height)) { return; } size = new Size(size.Width, size.Height - ReservedSpace); tickLen = -size.Width; startPoint = new Point(size.Width, size.Height + halfReservedSpace); endPoint = new Point(size.Width, halfReservedSpace); logicalToPhysical = size.Height / range * -1; progression = -1; break; case TickBarPlacement.Right: if (DoubleUtil.GreaterThanOrClose(ReservedSpace, size.Height)) { return; } size = new Size(size.Width, size.Height - ReservedSpace); tickLen = size.Width; startPoint = new Point(0d, size.Height + halfReservedSpace); endPoint = new Point(0d, halfReservedSpace); logicalToPhysical = size.Height / range * -1; progression = -1; break; } ; tickLen2 = tickLen * 0.75; // Invert direciton of the ticks if (IsDirectionReversed) { progression = -progression; logicalToPhysical *= -1; // swap startPoint & endPoint Point pt = startPoint; startPoint = endPoint; endPoint = pt; } Pen pen = new Pen(Fill, 1.0d); bool snapsToDevicePixels = false;//SnapsToDevicePixels DoubleCollection xLines = snapsToDevicePixels ? new DoubleCollection() : null; DoubleCollection yLines = snapsToDevicePixels ? new DoubleCollection() : null; // Is it Vertical? if ((Placement == TickBarPlacement.Left) || (Placement == TickBarPlacement.Right)) { // Reduce tick interval if it is more than would be visible on the screen double interval = TickFrequency; if (interval > 0.0) { double minInterval = (Maximum - Minimum) / size.Height; if (interval < minInterval) { interval = minInterval; } } // Draw Min & Max tick dc.DrawLine(pen, startPoint, new Point(startPoint.X + tickLen, startPoint.Y)); dc.DrawLine(pen, new Point(startPoint.X, endPoint.Y), new Point(startPoint.X + tickLen, endPoint.Y)); if (snapsToDevicePixels) { xLines.Add(startPoint.X); yLines.Add(startPoint.Y - 0.5); xLines.Add(startPoint.X + tickLen); yLines.Add(endPoint.Y - 0.5); xLines.Add(startPoint.X + tickLen2); } // This property is rarely set so let's try to avoid the GetValue // caching of the mutable default value DoubleCollection ticks = null; if (GetValue(TicksProperty) != null) { ticks = Ticks; } // Draw ticks using specified Ticks collection if ((ticks != null) && (ticks.Count > 0)) { for (int i = 0; i < ticks.Count; i++) { if (DoubleUtil.LessThanOrClose(ticks[i], Minimum) || DoubleUtil.GreaterThanOrClose(ticks[i], Maximum)) { continue; } double adjustedTick = ticks[i] - Minimum; double y = adjustedTick * logicalToPhysical + startPoint.Y; dc.DrawLine(pen, new Point(startPoint.X, y), new Point(startPoint.X + tickLen2, y)); if (snapsToDevicePixels) { yLines.Add(y - 0.5); } } } // Draw ticks using specified TickFrequency else if (interval > 0.0) { for (double i = interval; i < range; i += interval) { double y = i * logicalToPhysical + startPoint.Y; dc.DrawLine(pen, new Point(startPoint.X, y), new Point(startPoint.X + tickLen2, y)); if (snapsToDevicePixels) { yLines.Add(y - 0.5); } } } // Draw Selection Ticks if (IsSelectionRangeEnabled) { double y0 = (SelectionStart - Minimum) * logicalToPhysical + startPoint.Y; Point pt0 = new Point(startPoint.X, y0); Point pt1 = new Point(startPoint.X + tickLen2, y0); Point pt2 = new Point(startPoint.X + tickLen2, y0 + Math.Abs(tickLen2) * progression); //PathSegment[] segments = new PathSegment[] { // //new LineSegment(pt2, true), // //new LineSegment(pt0, true), // new LineSegment{Point=pt2 }, // new LineSegment{Point=pt0 }, //}; PathSegments segments = new PathSegments(); segments.Add(new LineSegment { Point = pt2 }); segments.Add(new LineSegment { Point = pt0 }); PathGeometry geo = new PathGeometry { Figures = new PathFigures { new PathFigure { StartPoint = pt1, Segments = segments, IsClosed = true } } }; dc.DrawGeometry(Fill, pen, geo); y0 = (SelectionEnd - Minimum) * logicalToPhysical + startPoint.Y; pt0 = new Point(startPoint.X, y0); pt1 = new Point(startPoint.X + tickLen2, y0); pt2 = new Point(startPoint.X + tickLen2, y0 - Math.Abs(tickLen2) * progression); segments = new PathSegments(); segments.Add(new LineSegment { Point = pt2 }); segments.Add(new LineSegment { Point = pt0 }); geo = new PathGeometry { Figures = new PathFigures { new PathFigure { StartPoint = pt1, Segments = segments, IsClosed = true } } }; dc.DrawGeometry(Fill, pen, geo); } } else // Placement == Top || Placement == Bottom { // Reduce tick interval if it is more than would be visible on the screen double interval = TickFrequency; if (interval > 0.0) { double minInterval = (Maximum - Minimum) / size.Width; if (interval < minInterval) { interval = minInterval; } } // Draw Min & Max tick dc.DrawLine(pen, startPoint, new Point(startPoint.X, startPoint.Y + tickLen)); dc.DrawLine(pen, new Point(endPoint.X, startPoint.Y), new Point(endPoint.X, startPoint.Y + tickLen)); if (snapsToDevicePixels) { xLines.Add(startPoint.X - 0.5); yLines.Add(startPoint.Y); xLines.Add(startPoint.X - 0.5); yLines.Add(endPoint.Y + tickLen); yLines.Add(endPoint.Y + tickLen2); } // This property is rarely set so let's try to avoid the GetValue // caching of the mutable default value DoubleCollection ticks = null; if (GetValue(TicksProperty) != null) { ticks = Ticks; } // Draw ticks using specified Ticks collection if ((ticks != null) && (ticks.Count > 0)) { for (int i = 0; i < ticks.Count; i++) { if (DoubleUtil.LessThanOrClose(ticks[i], Minimum) || DoubleUtil.GreaterThanOrClose(ticks[i], Maximum)) { continue; } double adjustedTick = ticks[i] - Minimum; double x = adjustedTick * logicalToPhysical + startPoint.X; dc.DrawLine(pen, new Point(x, startPoint.Y), new Point(x, startPoint.Y + tickLen2)); if (snapsToDevicePixels) { xLines.Add(x - 0.5); } } } // Draw ticks using specified TickFrequency else if (interval > 0.0) { for (double i = interval; i < range; i += interval) { double x = i * logicalToPhysical + startPoint.X; dc.DrawLine(pen, new Point(x, startPoint.Y), new Point(x, startPoint.Y + tickLen2)); if (snapsToDevicePixels) { xLines.Add(x - 0.5); } } } // Draw Selection Ticks if (IsSelectionRangeEnabled) { double x0 = (SelectionStart - Minimum) * logicalToPhysical + startPoint.X; Point pt0 = new Point(x0, startPoint.Y); Point pt1 = new Point(x0, startPoint.Y + tickLen2); Point pt2 = new Point(x0 + Math.Abs(tickLen2) * progression, startPoint.Y + tickLen2); //PathSegment[] segments = new PathSegment[] { // new LineSegment(pt2, true), // new LineSegment(pt0, true), //}; PathSegments segments = new PathSegments(); segments.Add(new LineSegment { Point = pt2 }); segments.Add(new LineSegment { Point = pt0 }); PathGeometry geo = new PathGeometry { Figures = new PathFigures { new PathFigure { StartPoint = pt1, Segments = segments, IsClosed = true } } }; dc.DrawGeometry(Fill, pen, geo); x0 = (SelectionEnd - Minimum) * logicalToPhysical + startPoint.X; pt0 = new Point(x0, startPoint.Y); pt1 = new Point(x0, startPoint.Y + tickLen2); pt2 = new Point(x0 - Math.Abs(tickLen2) * progression, startPoint.Y + tickLen2); segments = new PathSegments(); segments.Add(new LineSegment { Point = pt2 }); segments.Add(new LineSegment { Point = pt0 }); geo = new PathGeometry { Figures = new PathFigures { new PathFigure { StartPoint = pt1, Segments = segments, IsClosed = true } } }; dc.DrawGeometry(Fill, pen, geo); } } if (snapsToDevicePixels) { xLines.Add(Width); yLines.Add(Height); VisualXSnappingGuidelines = xLines; VisualYSnappingGuidelines = yLines; } return; }
protected override void OnRender(DrawingContext drawingContext) { var backgroundRect = new Rect(0, 0, this.ActualWidth, this.ActualHeight); drawingContext.DrawRectangle(Brushes.Black, null, backgroundRect); if (MapPoints == null) { return; } var minX = MapPoints.Min(p => p.Longitude); var maxX = MapPoints.Max(p => p.Longitude); var minY = MapPoints.Min(p => p.Latitude); var maxY = MapPoints.Max(p => p.Latitude); var mDistX = maxX - minX; //the maximum X distance between points var mDistY = maxY - minY; double scale; double offsetX = 5; //5 is a margin double offsetY = -5; double height = ActualHeight - 10; double width = ActualWidth - 10; if (mDistX >= mDistY) { scale = Math.Abs(width / mDistX); offsetY += (height - (mDistY * scale)) / 2d; } else { scale = Math.Abs(height / mDistY); offsetX += (width - (mDistX * scale)) / 2d; } Point?prevPoint = null; foreach (var point in MapPoints) { //calc coordinates for this point var x = ((point.Longitude - minX) * scale) + offsetX; var y = (height - ((point.Latitude - minY) * scale)) - offsetY; //draw its marker drawingContext.DrawRectangle(Brushes.Magenta, null, new Rect(x - 3, y - 3, 6, 6)); //draw line to previous if able var thisPoint = new Point(x, y); if (prevPoint.HasValue) { drawingContext.DrawLine(new Pen(Brushes.Magenta, 2d), thisPoint, prevPoint.Value); } //set this as previous prevPoint = thisPoint; } //base.OnRender(drawingContext); //var formText = new FormattedText(string.Format("Points count: {0}", MapPoints.Count), // CultureInfo.InvariantCulture, // FlowDirection.LeftToRight, // new Typeface("Verdana"), // 24, // Brushes.Magenta); //drawingContext.DrawText(formText, new Point(0, 0)); }
private void DrawTriangle() { int[] xPoints = new int[] { Convert.ToInt32(AX), Convert.ToInt32(BX), Convert.ToInt32(CX) }; int[] yPoints = new int[] { Convert.ToInt32(AY), Convert.ToInt32(BY), Convert.ToInt32(CY) }; int xMin = 0; int yMin = 0; if (xPoints.Min() < 0) { xMin = xPoints.Min(); } if (yPoints.Min() < 0) { yMin = yPoints.Min(); } int height = (yPoints.Max() + (-yMin)) * 100; int width = (xPoints.Max() + (-xMin)) * 100; Image myImage = new Image(); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); drawingContext.DrawLine(new Pen(Brushes.Green, 1), new Point(CX, CY), new Point(BX, BY)); drawingContext.DrawLine(new Pen(Brushes.Black, 1), new Point(CX, CY), new Point(AX, AY)); drawingContext.DrawLine(new Pen(Brushes.Red, 1), new Point(AX * 300, AY * 300), new Point(BX * 300, BY * 300)); drawingContext.Close(); RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 100, 100, PixelFormats.Pbgra32); bmp.Render(drawingVisual); myImage.Source = bmp; MainCanvas.Children.Add(myImage); using (FileStream stream = new FileStream("ColorSamples.png", FileMode.Create)) { PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmp)); encoder.Save(stream); } //if (MainCanvas.Children.Count >= 1) //{ // MainCanvas.Children.Clear(); //} //StackPanel stackPanel = new StackPanel(); //double multipler = 30;/* * MainCanvas.ActualWidth * 10 / 100;*/ //Line ABline = new Line(); //ABline.Stroke = Brushes.Red; //ABline.X1 = AX * multipler; //ABline.X2 = BX * multipler; //ABline.Y1 = AY * multipler; //ABline.Y2 = BY * multipler; //ABline.StrokeThickness = 1; //ABline.HorizontalAlignment = HorizontalAlignment.Right; //ABline.VerticalAlignment = VerticalAlignment.Bottom; //MainCanvas.Children.Add(ABline); //Line BCline = new Line(); //BCline.Stroke = Brushes.Black; //BCline.X1 = BX * multipler; //BCline.X2 = CX * multipler; //BCline.Y1 = BY * multipler; //BCline.Y2 = CY * multipler; //BCline.StrokeThickness = 1; //BCline.HorizontalAlignment = HorizontalAlignment.Right; //BCline.VerticalAlignment = VerticalAlignment.Bottom; //MainCanvas.Children.Add(BCline); //Line CAline = new Line(); //CAline.Stroke = Brushes.Green; //CAline.X1 = CX * multipler; //CAline.X2 = AX * multipler; //CAline.Y1 = CY * multipler; //CAline.Y2 = AY * multipler; //CAline.StrokeThickness = 1; //CAline.HorizontalAlignment = HorizontalAlignment.Right; //CAline.VerticalAlignment = VerticalAlignment.Bottom; //MainCanvas.Children. // Add(CAline); }
private void OnRender_BackgroundColor( DrawingContext dc, Color outerMain, Color outerEdgeStripes, Color outerGlow, Color innerMain, Color innerEdge, Color innerGlow, Color innerShadow) { var outerMainBrush = RenderToolFactory.GetTool <Brush> (new SolidColorBrushTool(outerMain)); var outerLeftGlowBrush = RenderToolFactory.GetTool <Brush> (new LinearGradientBrushTool(outerGlow, outerMain, 0, 0.3)); var outerRightGlowBrush = RenderToolFactory.GetTool <Brush> (new LinearGradientBrushTool(outerMain, outerGlow, 0, 0.3)); var shadowBrush = RenderToolFactory.GetTool <Brush> (new SolidColorBrushTool(innerShadow, 1 / 25f)); var innerMainBrush = RenderToolFactory.GetTool <Brush>(new SolidColorBrushTool(innerMain)); var innerEdgePen = RenderToolFactory.GetTool <Pen>(new PenTool(innerEdge, 1)); var innerGlowPen = RenderToolFactory.GetTool <Pen>(new PenTool(innerGlow, 0.5)); // Outer Area { dc.DrawRectangle(outerMainBrush, null, new Rect(0, 0, BOT_SCR_WIDTH, BOT_SCR_HEIGHT)); dc.DrawRectangle(outerLeftGlowBrush, null, new Rect(0, 0, 24, BOT_SCR_HEIGHT)); dc.DrawRectangle(outerRightGlowBrush, null, new Rect(BOT_SCR_WIDTH - 24, 0, 24, BOT_SCR_HEIGHT)); for (int i = 0; i < 7; i++) { var opacity = (1 - i / 7f) / 2; var pen = RenderToolFactory.GetTool <Pen>(new PenTool(outerEdgeStripes, 0.5, opacity)); dc.DrawLine(pen, new Point(0, BOT_SCR_HEIGHT - 4 * i - 2.5), new Point(BOT_SCR_WIDTH, BOT_SCR_HEIGHT - 4 * i - 2.5)); } } // Inner Area { const double RADIUS = 10; Rect area = new Rect(12, 39, BOT_SCR_WIDTH, 170); for (int pX = -2; pX <= 2; pX++) { for (int pY = -2; pY <= 2; pY++) { var offArea = area; offArea.Offset(pX, pY + 2); dc.DrawRoundedRectangle(shadowBrush, null, offArea, RADIUS, RADIUS); } } dc.DrawRoundedRectangle(innerMainBrush, innerEdgePen, area, RADIUS, RADIUS); Point p0 = new Point(area.X + RADIUS, area.Y + area.Height + 1); Point p1 = new Point(area.X + area.Width - 2 * RADIUS, area.Y + area.Height + 1); dc.DrawLine(innerGlowPen, p0, p1); } // Slots Area { for (int pX = 1; pX < 7; pX++) { for (int pY = 0; pY < 3; pY++) { const double GAP = BOT_SCR_WIDTH / 6.0; const double OFFSET = 31 + (170 - 2 * GAP) / 2; const double RADIUS = 2; Rect area = new Rect(GAP * pX - 8, Math.Floor(GAP * pY + OFFSET), 16, 16); Point p0 = new Point(area.X + RADIUS, area.Y); Point p1 = new Point(area.X + area.Width - RADIUS, area.Y); dc.DrawRoundedRectangle(null, innerEdgePen, area, RADIUS, RADIUS); dc.DrawLine(innerGlowPen, p0, p1); } } } }
/// <summary> /// When overridden in a derived class, participates in rendering operations that are directed by the layout system. /// The rendering instructions for this element are not used directly when this method is invoked, and are instead preserved for /// later asynchronous use by layout and drawing. /// </summary> /// <param name="drawingContext">The drawing instructions for a specific element. This context is provided to the layout system.</param> protected override void OnRender(DrawingContext drawingContext) { var dropInfo = DropInfo; if (dropInfo.VisualTarget is ItemsControl itemsControl) { // Get the position of the item at the insertion index. If the insertion point is // to be after the last item, then get the position of the last item and add an // offset later to draw it at the end of the list. ItemsControl itemParent; // Set to drop target's items container var visualTargetItem = dropInfo.VisualTargetItem; itemParent = visualTargetItem != null?ItemsControl.ItemsControlFromItemContainer(visualTargetItem) : itemsControl; // this could be happen with a thread scenario where items are removed very quickly if (itemParent == null) { return; } var itemsCount = itemParent.Items.Count; var index = Math.Min(dropInfo.InsertIndex, itemsCount - 1); var lastItemInGroup = false; var targetGroup = dropInfo.TargetGroup; if (targetGroup != null && targetGroup.IsBottomLevel && dropInfo.InsertPosition.HasFlag(RelativeInsertPosition.AfterTargetItem)) { var indexOf = targetGroup.Items.IndexOf(dropInfo.TargetItem); lastItemInGroup = indexOf == targetGroup.ItemCount - 1; if (lastItemInGroup && dropInfo.InsertIndex != itemsCount) { index--; } } var itemContainer = (UIElement)itemParent.ItemContainerGenerator.ContainerFromIndex(index); var showAlwaysDropTargetAdorner = itemContainer == null && DragDrop.GetShowAlwaysDropTargetAdorner(itemParent); if (showAlwaysDropTargetAdorner) { itemContainer = itemParent; } if (itemContainer != null) { // AdornedElement: control's ItemsPresenter var itemRect = new Rect(itemContainer.TranslatePoint(new Point(), AdornedElement), itemContainer.RenderSize); Point point1, point2; double rotation = 0; // I really don't know why I did this // // var viewportWidth = double.MaxValue; // var viewportHeight = double.MaxValue; // if (DropInfo.TargetScrollViewer != null) // { // if (DropInfo.TargetScrollViewer.ScrollableWidth != 0) // { // viewportWidth = DropInfo.TargetScrollViewer.ViewportWidth; // } // // if (DropInfo.TargetScrollViewer.ScrollableHeight != 0) // { // viewportHeight = DropInfo.TargetScrollViewer.ViewportHeight; // } // } if (dropInfo.VisualTargetOrientation == Orientation.Vertical) { if ((dropInfo.InsertIndex == itemsCount) || lastItemInGroup) { if (itemsCount > 0) { itemRect.Y += itemContainer.RenderSize.Height; } else { if ((itemsControl as ListView)?.View is GridView) { var header = itemsControl.FindVisualParent <GridViewHeaderRowPresenter>(); if (header != null) { itemRect.Y += header.RenderSize.Height; } } else if (itemsControl is DataGrid) { var header = itemsControl.FindVisualParent <DataGridColumnHeadersPresenter>(); if (header != null) { itemRect.Y += header.RenderSize.Height; } } itemRect.Y += Pen.Thickness; } } var itemRectRight = itemRect.Right; //Math.Min(itemRect.Right, viewportWidth); var itemRectLeft = itemRect.X < 0 ? 0 : itemRect.X; point1 = new Point(itemRectLeft, itemRect.Y); point2 = new Point(itemRectRight, itemRect.Y); } else { if (dropInfo.VisualTargetFlowDirection == FlowDirection.LeftToRight && dropInfo.InsertIndex == itemsCount) { if (itemsCount > 0) { itemRect.X += itemContainer.RenderSize.Width; } else { itemRect.X += Pen.Thickness; } } else if (dropInfo.VisualTargetFlowDirection == FlowDirection.RightToLeft && dropInfo.InsertIndex != itemsCount) { if (itemsCount > 0) { itemRect.X += itemContainer.RenderSize.Width; } else { itemRect.X += Pen.Thickness; } } var itemRectTop = itemRect.Y < 0 ? 0 : itemRect.Y; var itemRectBottom = itemRect.Bottom; //Math.Min(itemRect.Bottom, viewportHeight); point1 = new Point(itemRect.X, itemRectTop); point2 = new Point(itemRect.X, itemRectBottom); rotation = 90; } drawingContext.DrawLine(Pen, point1, point2); DrawTriangle(drawingContext, point1, rotation); DrawTriangle(drawingContext, point2, 180 + rotation); } } }
private void Draw(TreeViewItem parent, DrawingContext drawingContext) { var childCenter = new Point(); Point parentCenter = parent.TranslatePoint(new Point(), this); parentCenter.Offset(itemSize.Width / 2.0, itemSize.Height / 2.0); bool needVerticalLine = false; double verticalMidPointX = 0.0; bool isFirst = true; bool hasChildren = false; foreach (object child in parent.ItemContainerGenerator.Items) { var tvi = (TreeViewItem)parent.ItemContainerGenerator.ContainerFromItem(child); if (tvi == null) { continue; } childCenter = tvi.TranslatePoint(new Point(), this); childCenter.Offset(itemSize.Width / 2.0, itemSize.Height / 2.0); if (isFirst) { drawingContext.DrawLine(linePen, parentCenter, childCenter); isFirst = false; } else { hasChildren = true; if (needVerticalLine == false) { needVerticalLine = true; verticalMidPointX = parentCenter.X + (childCenter.X - parentCenter.X) / 2.0; } drawingContext.DrawLine( linePen, new Point(verticalMidPointX, childCenter.Y), childCenter ); } Draw(tvi, drawingContext); } if (hasChildren == false) { return; } drawingContext.DrawLine( linePen, new Point(verticalMidPointX, parentCenter.Y), new Point(verticalMidPointX, childCenter.Y + LineThickness / 2.0) ); }
protected override void OnRender(DrawingContext drawingContext) { base.OnRender(drawingContext); double xSize = 150.0; double ySize = 150.0; IEvolvableSkull organism = this.DataContext as IEvolvableSkull; //Get center point of whole shape int shapeWidth = organism.GenotypeWidths[Genes.FACE_GENE] + organism.GenotypeWidths[Genes.LEFTBONE_TOP_GENE] + organism.GenotypeWidths[Genes.RIGHTBONE_TOP_GENE]; int shapeHeight = organism.GenotypeHeights[Genes.FACE_GENE] + organism.GenotypeHeights[Genes.TEETH_GENE]; //Determine some offset values double offsetX = (xSize - shapeWidth) / 2; double offsetY = (ySize - shapeHeight) / 2; //************************************************************************************************************************** // THE ORDER IN WHICH THE GENES ARE DRAWN IS VERY IMPORTANT SO DONT MOVE ANY CODE // ORDER MUST BE //************************************************************************************************************************** //================================================================================================== // GENE[4] = Draw left top bone //================================================================================================== // Draw left top bone var leftBoneTopGeneBrush = new SolidColorBrush(organism.GenotypeColours[Genes.LEFTBONE_TOP_GENE]); drawingContext.DrawRectangle(leftBoneTopGeneBrush, new Pen(leftBoneTopGeneBrush, 0.0), new Rect( offsetX, offsetY, organism.GenotypeWidths[Genes.LEFTBONE_TOP_GENE], organism.GenotypeHeights[Genes.LEFTBONE_TOP_GENE])); drawingContext.DrawRectangle(Brushes.White, new Pen(Brushes.White, 0.0), new Rect( offsetX, (offsetY + (organism.GenotypeHeights[Genes.LEFTBONE_TOP_GENE] / 3)), (organism.GenotypeWidths[Genes.LEFTBONE_TOP_GENE] / 4), (organism.GenotypeHeights[Genes.LEFTBONE_TOP_GENE] / 3))); ////================================================================================================== //// GENE[7] = Draw left bottom bone ////================================================================================================== //// Draw left bottom bone var bottomBoneOffsetY = (offsetY + (organism.GenotypeHeights[Genes.FACE_GENE] - organism.GenotypeHeights[Genes.LEFTBONE_BOTTOM_GENE])); var leftBoneBottomGeneBrush = new SolidColorBrush(organism.GenotypeColours[Genes.LEFTBONE_BOTTOM_GENE]); drawingContext.DrawRectangle(leftBoneBottomGeneBrush, new Pen(leftBoneBottomGeneBrush, 0.0), new Rect( offsetX + (organism.GenotypeWidths[Genes.LEFTBONE_TOP_GENE] - organism.GenotypeWidths[Genes.LEFTBONE_BOTTOM_GENE]), bottomBoneOffsetY, organism.GenotypeWidths[Genes.LEFTBONE_BOTTOM_GENE], organism.GenotypeHeights[Genes.LEFTBONE_BOTTOM_GENE])); drawingContext.DrawRectangle(Brushes.White, new Pen(Brushes.White, 0.0), new Rect( offsetX + (organism.GenotypeWidths[Genes.LEFTBONE_TOP_GENE] - organism.GenotypeWidths[Genes.LEFTBONE_BOTTOM_GENE]), (bottomBoneOffsetY + (organism.GenotypeHeights[Genes.LEFTBONE_BOTTOM_GENE] / 3)), (organism.GenotypeWidths[Genes.LEFTBONE_BOTTOM_GENE] / 4), (organism.GenotypeHeights[Genes.LEFTBONE_BOTTOM_GENE] / 3))); //================================================================================================== // GENE[0] = Draw face rect //================================================================================================== offsetX += organism.GenotypeWidths[Genes.LEFTBONE_TOP_GENE]; // store faceX for use when drawing shapes var faceX = offsetX; // store faceY for use when drawing shapes var faceY = offsetY + organism.GenotypeHeights[Genes.FACE_GENE]; var faceGeneBrush = new SolidColorBrush(organism.GenotypeColours[Genes.FACE_GENE]); drawingContext.DrawRectangle(faceGeneBrush, new Pen(faceGeneBrush, 0.0), new Rect( offsetX, offsetY, organism.GenotypeWidths[Genes.FACE_GENE], organism.GenotypeHeights[Genes.FACE_GENE])); //================================================================================================== // GENE[5] = Draw right top bone //================================================================================================== // Draw right top bone offsetX += organism.GenotypeWidths[Genes.FACE_GENE]; var rightBoneTopGeneBrush = new SolidColorBrush(organism.GenotypeColours[Genes.RIGHTBONE_TOP_GENE]); drawingContext.DrawRectangle(rightBoneTopGeneBrush, new Pen(rightBoneTopGeneBrush, 0.0), new Rect( offsetX, offsetY, organism.GenotypeWidths[Genes.RIGHTBONE_TOP_GENE], organism.GenotypeHeights[Genes.RIGHTBONE_TOP_GENE])); drawingContext.DrawRectangle(Brushes.White, new Pen(Brushes.White, 0.0), new Rect( offsetX + organism.GenotypeWidths[Genes.RIGHTBONE_TOP_GENE] - (organism.GenotypeWidths[Genes.RIGHTBONE_TOP_GENE] / 4), (offsetY + (organism.GenotypeHeights[Genes.RIGHTBONE_TOP_GENE] / 3)), (organism.GenotypeWidths[Genes.RIGHTBONE_TOP_GENE] / 4), (organism.GenotypeHeights[Genes.RIGHTBONE_TOP_GENE] / 3))); ////================================================================================================== //// GENE[7] = Draw right bottom bone ////================================================================================================== //// Draw right bottom bone bottomBoneOffsetY = (offsetY + (organism.GenotypeHeights[Genes.FACE_GENE] - organism.GenotypeHeights[Genes.LEFTBONE_BOTTOM_GENE])); var rightBoneBottomGeneBrush = new SolidColorBrush(organism.GenotypeColours[Genes.RIGHTBONE_BOTTOM_GENE]); drawingContext.DrawRectangle(rightBoneBottomGeneBrush, new Pen(leftBoneBottomGeneBrush, 0.0), new Rect( offsetX, bottomBoneOffsetY, organism.GenotypeWidths[Genes.RIGHTBONE_BOTTOM_GENE], organism.GenotypeHeights[Genes.RIGHTBONE_BOTTOM_GENE])); drawingContext.DrawRectangle(Brushes.White, new Pen(Brushes.White, 0.0), new Rect( offsetX + organism.GenotypeWidths[Genes.RIGHTBONE_BOTTOM_GENE] - (organism.GenotypeWidths[Genes.RIGHTBONE_BOTTOM_GENE] / 4), (bottomBoneOffsetY + (organism.GenotypeHeights[Genes.RIGHTBONE_BOTTOM_GENE] / 3)), (organism.GenotypeWidths[Genes.RIGHTBONE_BOTTOM_GENE] / 4), (organism.GenotypeHeights[Genes.RIGHTBONE_BOTTOM_GENE] / 3))); //================================================================================================== // GENE[3] = Draw nose //================================================================================================== var nose_OffsetX = (faceX + (organism.GenotypeWidths[Genes.FACE_GENE] / 2)) - (organism.GenotypeWidths[Genes.NOSE_GENE] / 2); var nose_OffsetY = (faceY - (3 * organism.GenotypeHeights[Genes.NOSE_GENE])); // Draw jaw bone drawingContext.DrawRectangle(Brushes.Black, new Pen(Brushes.Black, 0.0), new Rect( nose_OffsetX, nose_OffsetY, organism.GenotypeWidths[Genes.NOSE_GENE], organism.GenotypeHeights[Genes.NOSE_GENE])); //================================================================================================== // GENE[1] = Draw left eye //================================================================================================== // store faceX + 1 eye width for use when drawing 1st eye var eyeLeftX = (xSize / 2) - (organism.GenotypeWidths[Genes.FACE_GENE] / 4); // store faceY + 1 eye height for use when drawing 1st eye var eyeLeftY = offsetY + (organism.GenotypeHeights[Genes.FACE_GENE] / 4); // draw the whole eye drawingContext.DrawEllipse(Brushes.Black, new Pen(Brushes.Black, 0.0), new Point(eyeLeftX, eyeLeftY), organism.GenotypeWidths[Genes.LEFT_EYE_GENE], organism.GenotypeHeights[Genes.LEFT_EYE_GENE]); // recalculate X position to put pupil into eye eyeLeftX = (eyeLeftX + (organism.GenotypeWidths[Genes.LEFT_EYE_GENE] / 4)); // recalculate Y position to put pupil into eye eyeLeftY = (eyeLeftY + (organism.GenotypeHeights[Genes.LEFT_EYE_GENE] / 4)); // draw pupil in eye - it is 1/2 the size of the whole eye var leftEyePupilColourBrush = new SolidColorBrush(organism.AvailableEyeColours[Genes.LEFT_EYE_GENE]); drawingContext.DrawEllipse(leftEyePupilColourBrush, new Pen(leftEyePupilColourBrush, 0.0), new Point(eyeLeftX, eyeLeftY), organism.GenotypeWidths[Genes.LEFT_EYE_GENE] / 2, organism.GenotypeHeights[Genes.LEFT_EYE_GENE] / 2); //================================================================================================== // GENE[2] = Draw right eye //================================================================================================== eyeLeftX = (xSize / 2) + (organism.GenotypeWidths[Genes.FACE_GENE] / 4); // store faceY + 1 eye height for use when drawing 1st eye eyeLeftY = offsetY + (organism.GenotypeHeights[Genes.FACE_GENE] / 4); // draw the whole eye drawingContext.DrawEllipse(Brushes.Black, new Pen(Brushes.Black, 0.0), new Point(eyeLeftX, eyeLeftY), organism.GenotypeWidths[Genes.LEFT_EYE_GENE], organism.GenotypeHeights[Genes.LEFT_EYE_GENE]); // recalculate X position to put pupil into eye eyeLeftX = (eyeLeftX + (organism.GenotypeWidths[Genes.RIGHT_EYE_GENE] / 4)); // recalculate Y position to put pupil into eye eyeLeftY = (eyeLeftY + (organism.GenotypeHeights[Genes.RIGHT_EYE_GENE] / 4)); // draw pupil in eye - it is 1/2 the size of the whole eye var rightEyePupilColourBrush = new SolidColorBrush(organism.AvailableEyeColours[Genes.LEFT_EYE_GENE]); drawingContext.DrawEllipse(rightEyePupilColourBrush, new Pen(rightEyePupilColourBrush, 0.0), new Point(eyeLeftX, eyeLeftY), organism.GenotypeWidths[Genes.LEFT_EYE_GENE] / 2, organism.GenotypeHeights[Genes.LEFT_EYE_GENE] / 2); //================================================================================================== // GENE[6] = Draw teeth (Actually jaw bone if one wanted to be pedantic) //================================================================================================== var jaw_OffsetX = (faceX + (organism.GenotypeWidths[Genes.FACE_GENE] / 2)) - (organism.GenotypeWidths[Genes.TEETH_GENE] / 2); offsetY = faceY; // Draw jaw bone var teethColourBrush = new SolidColorBrush(organism.AvailableEyeColours[Genes.TEETH_GENE]); drawingContext.DrawRectangle(teethColourBrush, new Pen(teethColourBrush, 0.0), new Rect( jaw_OffsetX, offsetY, organism.GenotypeWidths[Genes.TEETH_GENE], organism.GenotypeHeights[Genes.TEETH_GENE])); //Draw individual teeth into jaw bone - always drawn black // Work out spacing for teeth and store for use when drawing shapes var individual_tooth_OffsetX = (int)(organism.GenotypeWidths[Genes.TEETH_GENE] / 4); // Tooth1 drawingContext.DrawLine(new Pen(Brushes.Black, 1.0), new Point(jaw_OffsetX + individual_tooth_OffsetX, offsetY), new Point(jaw_OffsetX + individual_tooth_OffsetX, offsetY + organism.GenotypeHeights[Genes.TEETH_GENE])); // Tooth2 (Offset from tooth1) jaw_OffsetX += individual_tooth_OffsetX; drawingContext.DrawLine(new Pen(Brushes.Black, 1.0), new Point(jaw_OffsetX + individual_tooth_OffsetX, offsetY), new Point(jaw_OffsetX + individual_tooth_OffsetX, offsetY + organism.GenotypeHeights[Genes.TEETH_GENE])); // Tooth3 (Offset from tooth2) jaw_OffsetX += individual_tooth_OffsetX; drawingContext.DrawLine(new Pen(Brushes.Black, 1.0), new Point(jaw_OffsetX + individual_tooth_OffsetX, offsetY), new Point(jaw_OffsetX + individual_tooth_OffsetX, offsetY + organism.GenotypeHeights[Genes.TEETH_GENE])); }
protected override void OnRender(DrawingContext dc, double renderWidth) { // This may be true if the UI for a column hasn't been loaded yet (e.g., restoring multiple tabs from workspace won't load each tab until it's clicked by the user) if (gridPen == null) { if (UiWrapper != null && PresentationSource.FromVisual(UiWrapper) != null) { Matrix m = PresentationSource.FromVisual(UiWrapper).CompositionTarget.TransformToDevice; double dpiFactor = 1 / m.M11; gridPen = new Pen(Application.Current.TryFindResource("BorderThinBrush") as Brush, 1 * dpiFactor); halfPenWidth = gridPen.Thickness * 0.5; } } columnWidth = renderWidth; gridHeight = -gridPen.Thickness; double verticalOffset = -gridPen.Thickness; // If SuperDom scrolls so that editing price goes off the grid, hide the textbox until the editing price is visible again if (SuperDom.IsConnected) { if (tbNotes.Visibility == Visibility.Visible && SuperDom.Rows.All(r => r.Price != currentEditingPrice)) { tbNotes.Visibility = Visibility.Hidden; } if (tbNotes.Visibility == Visibility.Hidden && SuperDom.Rows.Any(r => r.Price == currentEditingPrice)) { tbNotes.Visibility = Visibility.Visible; } } lock (SuperDom.Rows) foreach (PriceRow row in SuperDom.Rows) { // Add new prices if needed to the dictionary as the user scrolls PriceStringValues.AddOrUpdate(row.Price, string.Empty, (key, oldValue) => oldValue); // If textbox is open, move it when the SuperDom scrolls if (tbNotes.Visibility == Visibility.Visible && row.Price == currentEditingPrice) { if (SuperDom.Rows.IndexOf(row) != gridIndex) { gridIndex = SuperDom.Rows.IndexOf(row); double tbOffset = gridIndex * SuperDom.ActualRowHeight; tbNotes.Margin = new Thickness(0, tbOffset, 0, 0); } } // Draw cell if (renderWidth - halfPenWidth >= 0) { Rect rect = new Rect(-halfPenWidth, verticalOffset, renderWidth - halfPenWidth, SuperDom.ActualRowHeight); // Create a guidelines set GuidelineSet guidelines = new GuidelineSet(); guidelines.GuidelinesX.Add(rect.Left + halfPenWidth); guidelines.GuidelinesX.Add(rect.Right + halfPenWidth); guidelines.GuidelinesY.Add(rect.Top + halfPenWidth); guidelines.GuidelinesY.Add(rect.Bottom + halfPenWidth); dc.PushGuidelineSet(guidelines); dc.DrawRectangle(BackColor, null, rect); dc.DrawLine(gridPen, new Point(-gridPen.Thickness, rect.Bottom), new Point(renderWidth - halfPenWidth, rect.Bottom)); dc.DrawLine(gridPen, new Point(rect.Right, verticalOffset), new Point(rect.Right, rect.Bottom)); // Print note value - remember to set MaxTextWidth so text doesn't spill into another column string note; if (PriceStringValues.TryGetValue(row.Price, out note) && !string.IsNullOrEmpty(PriceStringValues[row.Price])) { fontFamily = SuperDom.Font.Family; typeFace = new Typeface(fontFamily, SuperDom.Font.Italic ? FontStyles.Italic : FontStyles.Normal, SuperDom.Font.Bold ? FontWeights.Bold : FontWeights.Normal, FontStretches.Normal); if (renderWidth - 6 > 0) { FormattedText noteText = new FormattedText(note, Core.Globals.GeneralOptions.CurrentCulture, FlowDirection.LeftToRight, typeFace, SuperDom.Font.Size, ForeColor) { MaxLineCount = 1, MaxTextWidth = renderWidth - 6, Trimming = TextTrimming.CharacterEllipsis }; dc.DrawText(noteText, new Point(0 + 4, verticalOffset + (SuperDom.ActualRowHeight - noteText.Height) / 2)); } } dc.Pop(); verticalOffset += SuperDom.ActualRowHeight; gridHeight += SuperDom.ActualRowHeight; } } }
protected override void OnRender(DrawingContext drawingContext) { base.OnRender(drawingContext); drawingContext.DrawLine(pen, new Point(x, 0), new Point(x, bottom - top)); }
protected override void OnRender(DrawingContext dx) { base.OnRender(dx); if (ViewModel == null) { return; } var vertical = ViewModel.Vertical; var lengthRatio = ViewModel.LengthRatio; var sizeRatio = ViewModel.SizeRatio; var rulerInLength = ViewModel.RulerLength; var rulerStart = ViewModel.RulerStart; var rulerEnd = ViewModel.RulerEnd; var revert = ViewModel.Revert; var zero = ViewModel.Zero; var pixelsPerDip = 96 / ViewModel.Screen.RealDpiAvg; var rwidth = (vertical?ViewModel.RatioX:ViewModel.RatioY) * 30; var penIn = new Pen(Brushes.WhiteSmoke, 1); var penOut = new Pen(new SolidColorBrush(Color.FromScRgb(0.7f, 0.7f, 0.7f, 0.7f)), 1); //int mm = (int)rulerLengthOut - (int)ViewModel.DrawOn.InMm.Height; var mm = (int)rulerStart; if (vertical) { dx.DrawRectangle(ViewModel.BackgroundOut, null, new Rect(new Point(0, 0), new Point(rwidth, zero))); dx.DrawRectangle(ViewModel.BackgroundOut, null, new Rect(new Point(0, zero + rulerInLength * lengthRatio), new Point(rwidth, zero + rulerEnd * lengthRatio))); dx.DrawRectangle(ViewModel.Background, null, new Rect(new Point(0, zero), new Point(rwidth, zero + rulerInLength * lengthRatio))); } else { dx.DrawRectangle(ViewModel.BackgroundOut, null, new Rect(new Point(0, 0), new Point(zero, rwidth))); dx.DrawRectangle(ViewModel.BackgroundOut, null, new Rect(new Point(zero + rulerInLength * lengthRatio, 0), new Point(zero + rulerEnd * lengthRatio, rwidth))); dx.DrawRectangle(ViewModel.Background, null, new Rect(new Point(zero, 0), new Point(zero + rulerInLength * lengthRatio, rwidth))); } while (mm < (int)rulerEnd + 1) { var pos = zero + mm * lengthRatio; var size = sizeRatio; string text = null; var pen = (mm <0 || mm> rulerInLength) ? penOut : penIn; //if (mm >= rulerLength + 1) //{ // pos = rulerLength * lengthRatio; // size *= 30.0; // pen = penRed; //} //else if (mm >= rulerLength) //{ // pos = rulerLength * lengthRatio; // size *= 30.0; // pen = penRed; //} //else if (mm == 0) //{ // size *= 30.0; // pen = penRed; //} //else if (mm % 100 == 0) { size *= 20.0; text = (mm / 100).ToString(); } else if (mm % 50 == 0) { size *= 15.0; text = "5"; } else if (mm % 10 == 0) { size *= 10.0; text = ((mm % 100) / 10).ToString(); } else if (mm % 5 == 0) { size *= 5.0; } else { size *= 2.5; } if (text != null) { var t = new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Segoe UI"), size / 3, pen.Brush, pixelsPerDip); var p2 = (!revert) ? (size - size / 3) : (rwidth - size); dx.DrawText(t, vertical ? new Point(p2, pos) : new Point(pos, p2)); } var x0 = /*x +*/ (vertical ? ((revert) ? rwidth - size : 0) : pos); var x1 = /*x +*/ (vertical ? ((revert) ? rwidth : size) : pos); var y0 = /*y + */ (vertical ? pos : (revert ? rwidth - size : 0)); var y1 = /*y +*/ (vertical ? pos : ((revert) ? rwidth : size)); pen.Thickness = 0.1 * lengthRatio; dx.DrawLine(pen, new Point(x0, y0), new Point(x1, y1)); mm++; } }
public void draw() { try { using (DrawingContext dc = this.drawingGroup.Open()) { if (data_count > 0) { dc.DrawRectangle(Brushes.Black, null, new System.Windows.Rect(0.0, 0.0, 1000, 450)); drawTextLabel_FixSet(dc); drawTextFrameRate(dc); Boolean afterBreak = true; //-------------------------------------- int size_x1 = 22; int size_x1_half = size_x1 / 2; int size_x1_e = size_x1 + 3;//wioth border/edge int size_x1_e_half = size_x1_e / 2; int size_y0 = 200; int size_y1 = 27; //-------- int x_temp; int y_temp; int x1; int y0; int y1; int y2; int y3; int y4; int y0_f; int y1_f; int y2_f; int y3_f; int y_diff_0_1; x1 = 150; y0 = 60; y1 = 265; y2 = 295; y3 = 325; y4 = 375; y0_f = y0 + size_y0; y1_f = y1 + size_y1; y2_f = y2 + size_y1; y3_f = y3 + size_y1; y_diff_0_1 = y1 - y0; int y_map; Point line_p2 = new Point(x1, y0_f); Point line_p1 = line_p2; Point line1_p2 = new Point(x1, y1_f); Point line1_p1 = line1_p2; Point line2_p2 = new Point(x1, y2_f); Point line2_p1 = line2_p2; Point line3_p2 = new Point(x1, y3_f); Point line3_p1 = line3_p2; Brush brush_1 = Brushes.DarkMagenta; Pen drawingPen_1 = new Pen(brush_1, 2); Brush brush_2 = Brushes.Orange; Pen drawingPen_2 = new Pen(brush_2, 2); Pen drawingPen_headText = new Pen(Brushes.White, 3); SolidColorBrush sb0 = new SolidColorBrush(Color.FromArgb(255, 125, 125, 125)); SolidColorBrush sb1; SolidColorBrush sb2; SolidColorBrush sb3; SolidColorBrush sb4; for (int i = 0; i < data_count; i++) { DetectorReportData data = report_data_35List_array[i]; //-- Head Text -------------- if (i % 6 == 0) { dc.DrawLine(drawingPen_headText, new Point(x1, y0 - 10), new Point(x1, y0 + 10)); drawTextLabel(dc, data.time, x1, y0 - 30); } //-- BG Color ------------------------ if (data.flag_break != 1) { sb1 = getBrush_byHRL_xlv(data.total_lv); sb2 = getBrush_byHRL_3lv(data.twist_lv); sb3 = getBrush_byHRL_3lv(data.pitch_lv); sb4 = getBrush_byHRL_3lv(data.prolong_lv); } else { sb1 = sb0; sb2 = sb0; sb3 = sb0; sb4 = sb0; } dc.DrawRectangle(sb1, null, new System.Windows.Rect(x1, y0, size_x1, size_y0)); dc.DrawRectangle(sb2, null, new System.Windows.Rect(x1, y1, size_x1, size_y1)); dc.DrawRectangle(sb3, null, new System.Windows.Rect(x1, y2, size_x1, size_y1)); dc.DrawRectangle(sb4, null, new System.Windows.Rect(x1, y3, size_x1, size_y1)); //------------------------------- x_temp = x1 + size_x1_e_half; y_temp = y4; //--------------------------------- if (data.flag_break == 0) { //--- Line ----------------------- y_map = mapPosition(data.total_score, 100, y0, y0_f); drawLine(dc, drawingPen_1, brush_1, ref line_p1, ref line_p2, x_temp, y_map, afterBreak); if (checkChangeInData(i, 0) || afterBreak) { dc.DrawEllipse(brush_1, null, line_p2, 4, 4); } // if (checkLine.IsChecked.Value) { y_map = mapPosition(data.twist_score, 60, y1, y1_f); drawLine(dc, drawingPen_2, brush_2, ref line1_p1, ref line1_p2, x_temp, y_map, afterBreak); if (checkChangeInData(i, 1) || afterBreak) { dc.DrawEllipse(brush_2, null, line1_p2, 4, 4); } //---- // y_map = mapPosition(data.pitch_score, 60, y2, y2_f); drawLine(dc, drawingPen_2, brush_2, ref line2_p1, ref line2_p2, x_temp, y_map, afterBreak); if (checkChangeInData(i, 2) || afterBreak) { dc.DrawEllipse(brush_2, null, line2_p2, 4, 4); } //---- // y_map = mapPosition(data.prolong_score, 240, y3, y3_f); drawLine(dc, drawingPen_2, brush_2, ref line3_p1, ref line3_p2, x_temp, y_map, afterBreak); if (checkChangeInData(i, 3) || afterBreak) { dc.DrawEllipse(brush_2, null, line3_p2, 4, 4); } } //--- First Icon ------------------- if (data.flag_stand == 1) { drawIcon(dc, 9, x_temp, y_temp); y_temp += 25; if (data.flag_move == 1) { drawIcon(dc, 12, x_temp, y_temp); y_temp += 25; } } else { if (data.flag_move == 1) { drawIcon(dc, 12, x_temp, y_temp); y_temp += 25; } else { if (data.flag_pitch == 1) { drawIcon(dc, 11, x_temp, y_temp); y_temp += 25; } if (data.flag_twist == 1) { drawIcon(dc, 21, x_temp - 5, y_temp); y_temp += 25; } if (data.flag_twist == -1) { drawIcon(dc, 22, x_temp + 5, y_temp); y_temp += 25; } } } afterBreak = false; } else { if (afterBreak == false) { drawLine_endBreak(dc, drawingPen_1, line_p2, size_x1_e_half); if (checkLine.IsChecked.Value) { drawLine_endBreak(dc, drawingPen_2, line1_p2, 10); drawLine_endBreak(dc, drawingPen_2, line2_p2, 10); drawLine_endBreak(dc, drawingPen_2, line3_p2, 10); } } afterBreak = true; } //------------------- x1 += size_x1 + 2; } //---- Draw Line End for the last record ----- drawLine_endBreak(dc, drawingPen_1, line_p2, size_x1_e_half); if (checkLine.IsChecked.Value) { drawLine_endBreak(dc, drawingPen_2, line1_p2, 10); drawLine_endBreak(dc, drawingPen_2, line2_p2, 10); drawLine_endBreak(dc, drawingPen_2, line3_p2, 10); } } } } catch //(Exception ex) { //TheSys.showError("Draw:" + ex.Message); } }
public override void DrawEquation(DrawingContext dc) { switch (decorationType) { case DecorationType.Bar: dc.DrawLine(ThinPen, Location, new Point(Right, Top)); break; case DecorationType.DoubleBar: dc.DrawLine(ThinPen, Location, new Point(Right, Top)); dc.DrawLine(ThinPen, new Point(Left, Bottom - ThinPen.Thickness), new Point(Right, Bottom - ThinPen.Thickness)); break; case DecorationType.Hat: dc.DrawPolyline(new Point(Left, Bottom - FontSize * .02), new PointCollection { new Point(MidX, Top + FontSize * .03), new Point(Right, Bottom - FontSize * .02) }, ThinPen); break; case DecorationType.LeftArrow: firstSign.DrawTextTopLeftAligned(dc, Location); dc.DrawLine(ThinPen, new Point(Left + FontSize * .06, MidY), new Point(Right, MidY)); break; case DecorationType.RightArrow: firstSign.DrawTextTopRightAligned(dc, new Point(Right, Top)); dc.DrawLine(ThinPen, new Point(Left, MidY), new Point(Right - FontSize * .06, MidY)); break; case DecorationType.DoubleArrow: DrawDoubleArrow(dc); break; case DecorationType.Parenthesis: DrawParentheses(dc); break; case DecorationType.RightHarpoonUpBarb: DrawRightHarpoonUpBarb(dc); break; case DecorationType.RightHarpoonDownBarb: DrawRightHarpoonDownBarb(dc); break; case DecorationType.LeftHarpoonUpBarb: DrawLeftHarpoonUpBarb(dc); break; case DecorationType.LeftHarpoonDownBarb: DrawLeftHarpoonDownBarb(dc); break; case DecorationType.Tilde: firstSign.DrawTextTopLeftAligned(dc, Location); break; case DecorationType.Tortoise: DrawTortoise(dc); break; case DecorationType.Cross: dc.DrawLine(ThinPen, ParentEquation.Location, new Point(Right, ParentEquation.Bottom)); dc.DrawLine(ThinPen, new Point(Left, ParentEquation.Bottom), new Point(Right, ParentEquation.Top)); break; case DecorationType.LeftCross: dc.DrawLine(ThinPen, ParentEquation.Location, new Point(Right, ParentEquation.Bottom)); break; case DecorationType.RightCross: dc.DrawLine(ThinPen, new Point(Left, ParentEquation.Bottom), new Point(Right, ParentEquation.Top)); break; case DecorationType.StrikeThrough: dc.DrawLine(ThinPen, new Point(Left, ParentEquation.MidY), new Point(Right, ParentEquation.MidY)); break; } }
// Grid rendering private void RenderHorizontal(DrawingContext dc) { Pen p = new Pen(Brushes.Black, 1); Pen q = new Pen(Brushes.LightGray, 1); double padLeft = Padding.Left; double padBottom = Padding.Bottom - 2 + 10; double padTop = Padding.Top; double padRight = Padding.Right; // Draw horizontal gridlines double step_size = (MaxVal - MinVal) / (NumVertGrid - 1.0); for (int i = 0; i < NumVertGrid; i++) { double y = (int)(padTop + ((NumVertGrid - 1.0) - i) * ((ActualHeight - padBottom - padTop) / (NumVertGrid - 1.0))) - 0.5; double y_val = MinVal + i * step_size; if (y_val != 0) { dc.DrawLine(q, new Point(padLeft, y), new Point(ActualWidth - padRight, y)); } else { dc.DrawLine(p, new Point(padLeft, y), new Point(ActualWidth - padRight, y)); } dc.DrawLine(p, new Point(padLeft - 10, y), new Point(padLeft, y)); var t = FormT((MinVal + i * step_size).ToString("0.0"), 10); dc.DrawText(t, new Point(padLeft - t.Width - 12, y - t.Height / 2)); if (i == 0) { MinAxesY = y; } if (i == NumVertGrid - 1) { MaxAxesY = y; } } // Draw vertical gridlines for (int i = 0; i < 11; i++) { double x = (int)(padLeft + (10 - i) * ((ActualWidth - padLeft - padRight) / 10.0)) - 0.5; if (i < 10) { dc.DrawLine(q, new Point(x, ActualHeight - padBottom), new Point(x, padTop)); } dc.DrawLine(p, new Point(x, ActualHeight - padBottom + 10), new Point(x, ActualHeight - padBottom)); if (XTicks) { var t = FormT(i.ToString(), 10); dc.DrawText(t, new Point(x - t.Width / 2, ActualHeight - padBottom + t.Height)); } if (i == 0) { MaxAxesX = x; } if (i == (11 - 1)) { MinAxesX = x; } } // Draw y axis dc.DrawLine(p, new Point(((int)padLeft) - 0.5, padTop), new Point(((int)padLeft) - 0.5, ActualHeight - padBottom)); //dc.DrawLine(p, new Point(MinAxesX, MinAxesY), new Point(MaxAxesX, MaxAxesY)); //dc.DrawLine(p, new Point(MaxAxesX, padTop), new Point(MaxAxesX, ActualHeight - padBottom)); // Draw x axis label if (ShowXLabel) { FormattedText ft = FormT("History (seconds)", 20); dc.DrawText(ft, new Point(padLeft + (ActualWidth - padLeft - padRight) / 2 - ft.Width / 2, ActualHeight - ft.Height)); } // Draw y axis label if (ShowYLabel) { FormattedText ft = FormT(RangeLabel, 20); dc.PushTransform(new RotateTransform(-90)); dc.DrawText(ft, new Point(-ft.Width - ActualHeight / 2 + ft.Width / 2, 0)); dc.Pop(); } DataPointGraph[] localPoints; lock (dataPoints) localPoints = dataPoints.ToArray(); var pfs = new Dictionary <int, PathFigure>(); for (int i = 0; i < localPoints.Length; i++) { var ptTime = localPoints[i].Time; var ptAge = (DateTime.Now - ptTime).TotalSeconds; foreach (var kvp in localPoints[i].values) { var seriesId = kvp.Key; double v = (kvp.Value - MinVal) / (MaxVal - MinVal); // X starts here MinAxesX // X ends here MaxAxesX double y = MinAxesY - (MinAxesY - MaxAxesY) * v; double x = MaxAxesX - (CurrentTime - localPoints[i].Time).TotalMilliseconds * ((MaxAxesX - MinAxesX) / historyLength.TotalMilliseconds); // Make sure everything is within bounds if (x < MinAxesX) { continue; } y = Math.Min(MinAxesY, Math.Max(MaxAxesY, y)); if (!pfs.ContainsKey(seriesId)) { pfs[seriesId] = new PathFigure(); pfs[seriesId].IsClosed = false; pfs[seriesId].StartPoint = new Point(x, y); } else { pfs[seriesId].Segments.Add(new LineSegment(new Point(x, y), true)); } } } foreach (var kvp in pfs) { var seriesId = kvp.Key; var pf = kvp.Value; Brush b = brushes.ContainsKey(seriesId) ? brushes[seriesId] : Brushes.Black; int thickness = brush_thicknesses.ContainsKey(seriesId) ? brush_thicknesses[seriesId] : 2; PathGeometry pg = new PathGeometry(new PathFigure[] { pf }); Pen p2 = new Pen(b, thickness); dc.DrawGeometry(null, p2, pg); } if (ShowLegend && line_names.Count > 0) { int height_one = 18; int height = height_one * line_names.Count; Pen p2 = new Pen(Brushes.Black, 1); Brush legend_b = new SolidColorBrush(Color.FromRgb(255, 255, 255)); dc.DrawRectangle(legend_b, p2, new Rect(MinAxesX, MaxAxesY, 100, height)); int i = 0; foreach (var key_name_pair in line_names) { var line_name = key_name_pair.Value; FormattedText ft = FormT(line_name, 11); // Draw the text dc.DrawText(ft, new Point(MinAxesX + 15, MaxAxesY + 1 + height_one * i)); // Draw example lines Brush legend_c = new SolidColorBrush(brush_colors[key_name_pair.Key]); Pen p_line = new Pen(legend_c, brush_thicknesses[key_name_pair.Key]); dc.DrawLine(p_line, new Point(MinAxesX, MaxAxesY + height_one * i - 1 + height_one / 2), new Point(MinAxesX + 14, MaxAxesY - 1 + height_one * i + height_one / 2)); i++; } } }
protected override void OnRender(DrawingContext drawingContext) { _ghostBrush = (SolidColorBrush)FindResource(Globals.GhostBrush); _ghostPen = new Pen(_ghostBrush, Globals.BondThickness); HashSet <Bond> bondSet = new HashSet <Bond>(); Dictionary <Atom, Point> transformedPositions = new Dictionary <Atom, Point>(); //compile a set of all the neighbours of the selected atoms foreach (Atom atom in _atomList) { foreach (Atom neighbour in atom.Neighbours) { //add in all the existing position for neigbours not in selected atoms if (!_atomList.Contains(neighbour)) { //neighbourSet.Add(neighbour); //don't worry about adding them twice transformedPositions[neighbour] = neighbour.Position; } } //add in the bonds foreach (Bond bond in atom.Bonds) { bondSet.Add(bond); //don't worry about adding them twice } //if we're just getting an overlay then don't bother transforming if (_shear != null) { transformedPositions[atom] = _shear.Transform(atom.Position); } else { transformedPositions[atom] = atom.Position; } } var modelXamlBondLength = CurrentViewModel.Model.XamlBondLength; double atomRadius = modelXamlBondLength / 7.50; foreach (Bond bond in bondSet) { List <Point> throwaway = new List <Point>(); var startAtomPosition = transformedPositions[bond.StartAtom]; var endAtomPosition = transformedPositions[bond.EndAtom]; if (bond.OrderValue != 1.0 || !(bond.Stereo == Globals.BondStereo.Hatch | bond.Stereo == Globals.BondStereo.Wedge)) { var descriptor = BondVisual.GetBondDescriptor(CurrentEditor.GetAtomVisual(bond.StartAtom), CurrentEditor.GetAtomVisual(bond.EndAtom), modelXamlBondLength, bond.Stereo, startAtomPosition, endAtomPosition, bond.OrderValue, bond.Placement, bond.Centroid, bond.SubsidiaryRing?.Centroid); descriptor.Start = startAtomPosition; descriptor.End = endAtomPosition; var bondgeom = descriptor.DefiningGeometry; drawingContext.DrawGeometry(_ghostBrush, _ghostPen, bondgeom); } else { drawingContext.DrawLine(_ghostPen, startAtomPosition, endAtomPosition); } } foreach (Atom atom in transformedPositions.Keys) { var newPosition = transformedPositions[atom]; if (atom.SymbolText != "") { drawingContext.DrawEllipse(SystemColors.WindowBrush, _ghostPen, newPosition, atomRadius, atomRadius); } } }