public void OnLoad(MMF.Sprite.D2DSpriteBatch batch) { GameContext.InitializePlayerDescriptions(batch); _geometry = new PathGeometry(GameContext.RenderContext.D2DFactory); GeometrySink geometrySink = _geometry.Open(); geometrySink.SetFillMode(FillMode.Winding); geometrySink.BeginFigure(new Point(50, 580), FigureBegin.Filled); geometrySink.AddLine(new Point(20, 600)); geometrySink.AddLine(new Point(50, 620)); geometrySink.EndFigure(FigureEnd.Closed); geometrySink.Close(); _geometry_2 = new PathGeometry(GameContext.RenderContext.D2DFactory); GeometrySink geometrySink_2 = _geometry_2.Open(); geometrySink_2.SetFillMode(FillMode.Winding); geometrySink_2.BeginFigure(new Point(520, 580), FigureBegin.Filled); geometrySink_2.AddLine(new Point(550, 600)); geometrySink_2.AddLine(new Point(520, 620)); geometrySink_2.EndFigure(FigureEnd.Closed); geometrySink_2.Close(); col_1 = batch.CreateSolidColorBrush(Color.FromArgb(255, 255, 255, 255)); col_2 = batch.CreateSolidColorBrush(Color.FromArgb(120, 255, 0, 0)); col_3 = batch.CreateSolidColorBrush(Color.FromArgb(120, 0, 0, 255)); col_4 = batch.CreateSolidColorBrush(Color.FromArgb(120, 0, 255, 0)); col_5 = batch.CreateSolidColorBrush(Color.FromArgb(120, 0, 0, 0)); // bitmap = batch.CreateBitmap(@playerDescriptions[currentIndex].image); format_1 = batch.CreateTextformat("Meiryo UI", 60); format_2 = batch.CreateTextformat("Meiryo UI", 100); isInitialized = true; }
/// <summary> /// In a derived class, implements logic to initialize the sample. /// </summary> protected override void OnInitialize() { DeviceSettings2D settings = new DeviceSettings2D { Width = WindowWidth, Height = WindowHeight }; InitializeDevice(settings); geometry = new PathGeometry(Context2D.RenderTarget.Factory); using (GeometrySink sink = geometry.Open()) { PointF p0 = new PointF(0.50f * WindowWidth, 0.25f * WindowHeight); PointF p1 = new PointF(0.75f * WindowWidth, 0.75f * WindowHeight); PointF p2 = new PointF(0.25f * WindowWidth, 0.75f * WindowHeight); sink.BeginFigure(p0, FigureBegin.Filled); sink.AddLine(p1); sink.AddLine(p2); sink.EndFigure(FigureEnd.Closed); // Note that Close() and Dispose() are not equivalent like they are for // some other IDisposable() objects. sink.Close(); } brush = new SolidColorBrush(Context2D.RenderTarget, new Color4(0.93f, 0.40f, 0.08f)); }
protected override void OnCreateDeviceIndependentResources(Direct2DFactory factory) { base.OnCreateDeviceIndependentResources(factory); this._pathGeometry = factory.CreatePathGeometry(); using (GeometrySink sink = this._pathGeometry.Open()) { sink.SetFillMode(FillMode.Winding); sink.BeginFigure(new PointF(20, 50), FigureBegin.Filled); sink.AddLine(new PointF(130, 50)); sink.AddLine(new PointF(20, 130)); sink.AddLine(new PointF(80, 0)); sink.AddLine(new PointF(130, 130)); sink.EndFigure(FigureEnd.Closed); sink.Close(); } }
/// <summary> /// Creates the part. /// </summary> /// <returns> /// UIElement /// </returns> public override UIElement CreatePart() { SplinePath = new Path(); PathFigure figure = new PathFigure(); BezierSegment bezierPoints = new BezierSegment(); PathGeometry pathGeometry = new PathGeometry(); figure.StartPoint = StartPoint; bezierPoints.Point1 = FirstControlPoint; bezierPoints.Point2 = EndControlPoint; bezierPoints.Point3 = EndPoint; figure.Segments.Add(bezierPoints); pathGeometry.Figures = new PathFigureCollection() { figure }; SplinePath.Data = pathGeometry; SetBindingForStrokeandStrokeThickness(SplinePath); return SplinePath; }
/// <summary> /// Initializes a new instance of the <see cref="XGraphicsPath"/> class. /// </summary> public XGraphicsPath() { #if CORE _corePath = new CoreGraphicsPath(); #endif #if GDI try { Lock.EnterGdiPlus(); _gdipPath = new GraphicsPath(); } finally { Lock.ExitGdiPlus(); } #endif #if WPF || NETFX_CORE _pathGeometry = new PathGeometry(); #endif }
private void ModifyGeometry() { GeometrySink geometrySink; double which = Random.NextDouble(); if (which < 0.33) { geometryOutlined = d2DFactory.CreatePathGeometry(); geometrySink = geometryOutlined.Open(); geometry.Outline(geometrySink, FlatteningTolerance); geometrySink.Close(); geometrySink.Dispose(); geometry.Dispose(); geometry = geometryOutlined; } else if (which < 0.67) { geometrySimplified = d2DFactory.CreatePathGeometry(); geometrySink = geometrySimplified.Open(); geometry.Simplify( CoinFlip ? GeometrySimplificationOption.Lines : GeometrySimplificationOption.CubicsAndLines, geometrySink, FlatteningTolerance ); geometrySink.Close(); geometrySink.Dispose(); geometry.Dispose(); geometry = geometrySimplified; } else { geometryWidened = d2DFactory.CreatePathGeometry(); geometrySink = geometryWidened.Open(); geometry.Widen( RandomStrokeWidth(), //75 RandomStrokeStyle(), geometrySink, FlatteningTolerance); geometrySink.Close(); geometrySink.Dispose(); geometry.Dispose(); geometry = geometryWidened; } }
/// <summary> /// Create a visual for single Series Part /// </summary> /// <returns> /// UIElement /// </returns> public override UIElement CreatePart() { AreaPath = new Path(); PathFigure figure = new PathFigure(); LineSegment startLineSegment = new LineSegment(); LineSegment areaEndLineSegment = new LineSegment(); LineSegment endLineSegment = new LineSegment(); PathGeometry pathGeometry = new PathGeometry(); figure.StartPoint = StartPoint; startLineSegment.Point = AreaStartPoint; endLineSegment.Point = EndPoint; areaEndLineSegment.Point = AreaEndPoint; figure.Segments.Add(startLineSegment); figure.Segments.Add(areaEndLineSegment); figure.Segments.Add(endLineSegment); pathGeometry.Figures = new PathFigureCollection() { figure }; AreaPath.Data = pathGeometry; SetBindingForStrokeandStrokeThickness(AreaPath); return AreaPath; }
/// <summary> /// Converts a string of Path.Data into PathGeometry. /// </summary> /// <param name="pathStr">Path.Data in string form.</param> /// <returns>PathGeometry from data string</returns> /// <example> /// pathStr = "M532,181 L532,219 L571,219 L570.54004,180.9397 z"; /// var geometry = PathUtils.ParsePathGeometryString(pathStr); /// ArtefactAnimator.AddEase(myPath, Path.DataProperty, geometry, 3, AnimationTransitions.CubicEaseOut, 0); /// </example> public static PathGeometry ParsePathGeometryString ( string pathStr ) { // string too short or doesn't exist if ( pathStr == null || pathStr.Length < 2 )return new PathGeometry(); // groups representing segments var matches = PathGeometryExpression.Matches(pathStr); // single figure holding segements var figure = new PathFigure { Segments = new PathSegmentCollection(), StartPoint = new Point(), IsClosed = pathStr.Substring(pathStr.Length-1, 1).ToLower() == "z" }; // final path geometry var pathGeo = new PathGeometry { Figures = new PathFigureCollection{figure} }; // parse matches and put in figure for (var i = 0; i < matches.Count; i++) ParseMatch(figure, matches[i]); return pathGeo; }
/// <summary> /// Refreshes this instance. /// </summary> public override void Refresh() { if (SplinePath != null) { PathFigure figure = new PathFigure(); BezierSegment bezierPoints = new BezierSegment(); PathGeometry pathGeometry = new PathGeometry(); figure.StartPoint = StartPoint; bezierPoints.Point1 = FirstControlPoint; bezierPoints.Point2 = EndControlPoint; bezierPoints.Point3 = EndPoint; figure.Segments.Add(bezierPoints); pathGeometry.Figures = new PathFigureCollection() { figure }; SplinePath.Data = pathGeometry; } }
/// <summary> /// Initializes a new instance of the <see cref="XGraphicsPath"/> class. /// </summary> public XGraphicsPath(PointF[] points, byte[] types, XFillMode fillMode) { #if GDI try { Lock.EnterGdiPlus(); _gdipPath = new GraphicsPath(points, types, (FillMode)fillMode); } finally { Lock.ExitGdiPlus(); } #endif #if WPF // Is true only in Hybrid build. _pathGeometry = new PathGeometry(); _pathGeometry.FillRule = FillRule.EvenOdd; #endif }
private void DrawBorder(DrawingContext dc, ref Rect bounds) { if (bounds.Width >= 5.0 && bounds.Height >= 5.0) { Brush brush = this.BorderBrush; Pen pen = null; if (brush != null) { if (ImageButtonChromeControl._commonBorderPen == null) { lock (ImageButtonChromeControl._resourceAccess) { if (ImageButtonChromeControl._commonBorderPen == null) { if (!brush.IsFrozen && brush.CanFreeze) { brush = brush.Clone(); brush.Freeze(); } Pen pen2 = new Pen(brush, 1.0); if (pen2.CanFreeze) { pen2.Freeze(); ImageButtonChromeControl._commonBorderPen = pen2; } } } } if (ImageButtonChromeControl._commonBorderPen != null && brush == ImageButtonChromeControl._commonBorderPen.Brush) { pen = ImageButtonChromeControl._commonBorderPen; } else { if (!brush.IsFrozen && brush.CanFreeze) { brush = brush.Clone(); brush.Freeze(); } pen = new Pen(brush, 1.0); if (pen.CanFreeze) { pen.Freeze(); } } } Pen borderOverlayPen = this.BorderOverlayPen; if (pen != null || borderOverlayPen != null) { if (this.RoundCorners) { Rect rectangle = new Rect(bounds.Left + 0.5, bounds.Top + 0.5, bounds.Width - 1.0, bounds.Height - 1.0); if (base.IsEnabled && pen != null) { dc.DrawRoundedRectangle(null, pen, rectangle, 2.75, 2.75); } if (borderOverlayPen != null) { dc.DrawRoundedRectangle(null, borderOverlayPen, rectangle, 2.75, 2.75); return; } } else { PathFigure pathFigure = new PathFigure(); pathFigure.StartPoint = new Point(0.5, 0.5); pathFigure.Segments.Add(new LineSegment(new Point(0.5, bounds.Bottom - 0.5), true)); pathFigure.Segments.Add(new LineSegment(new Point(bounds.Right - 2.5, bounds.Bottom - 0.5), true)); pathFigure.Segments.Add(new ArcSegment(new Point(bounds.Right - 0.5, bounds.Bottom - 2.5), new Size(2.0, 2.0), 0.0, false, SweepDirection.Counterclockwise, true)); pathFigure.Segments.Add(new LineSegment(new Point(bounds.Right - 0.5, bounds.Top + 2.5), true)); pathFigure.Segments.Add(new ArcSegment(new Point(bounds.Right - 2.5, bounds.Top + 0.5), new Size(2.0, 2.0), 0.0, false, SweepDirection.Counterclockwise, true)); pathFigure.IsClosed = true; PathGeometry pathGeometry = new PathGeometry(); pathGeometry.Figures.Add(pathFigure); if (base.IsEnabled && pen != null) { dc.DrawGeometry(null, pen, pathGeometry); } if (borderOverlayPen != null) { dc.DrawGeometry(null, borderOverlayPen, pathGeometry); } } } } }
static SKPath MakePath(PathGeometry pathGeometry) { var path = new SKPath(); path.FillType = pathGeometry.FillRule == FillRule.Nonzero ? SKPathFillType.Winding : SKPathFillType.EvenOdd; foreach (PathFigure pathFigure in pathGeometry.Figures) { path.MoveTo( Forms.ConvertToScaledPixel(pathFigure.StartPoint.X), Forms.ConvertToScaledPixel(pathFigure.StartPoint.Y)); Point lastPoint = pathFigure.StartPoint; foreach (PathSegment pathSegment in pathFigure.Segments) { // LineSegment if (pathSegment is LineSegment) { LineSegment lineSegment = pathSegment as LineSegment; path.LineTo( Forms.ConvertToScaledPixel(lineSegment.Point.X), Forms.ConvertToScaledPixel(lineSegment.Point.Y)); lastPoint = lineSegment.Point; } // PolylineSegment else if (pathSegment is PolyLineSegment) { PolyLineSegment polylineSegment = pathSegment as PolyLineSegment; PointCollection points = polylineSegment.Points; for (int i = 0; i < points.Count; i++) { path.LineTo( Forms.ConvertToScaledPixel(points[i].X), Forms.ConvertToScaledPixel(points[i].Y)); } lastPoint = points[points.Count - 1]; } // BezierSegment else if (pathSegment is BezierSegment) { BezierSegment bezierSegment = pathSegment as BezierSegment; path.CubicTo( Forms.ConvertToScaledPixel(bezierSegment.Point1.X), Forms.ConvertToScaledPixel(bezierSegment.Point1.Y), Forms.ConvertToScaledPixel(bezierSegment.Point2.X), Forms.ConvertToScaledPixel(bezierSegment.Point2.Y), Forms.ConvertToScaledPixel(bezierSegment.Point3.X), Forms.ConvertToScaledPixel(bezierSegment.Point3.Y)); lastPoint = bezierSegment.Point3; } // PolyBezierSegment else if (pathSegment is PolyBezierSegment) { PolyBezierSegment polyBezierSegment = pathSegment as PolyBezierSegment; PointCollection points = polyBezierSegment.Points; for (int i = 0; i < points.Count; i += 3) { path.CubicTo( Forms.ConvertToScaledPixel(points[i + 0].X), Forms.ConvertToScaledPixel(points[i + 0].Y), Forms.ConvertToScaledPixel(points[i + 1].X), Forms.ConvertToScaledPixel(points[i + 1].Y), Forms.ConvertToScaledPixel(points[i + 2].X), Forms.ConvertToScaledPixel(points[i + 2].Y)); } lastPoint = points[points.Count - 1]; } // QuadraticBezierSegment else if (pathSegment is QuadraticBezierSegment) { QuadraticBezierSegment bezierSegment = pathSegment as QuadraticBezierSegment; path.QuadTo( Forms.ConvertToScaledPixel(bezierSegment.Point1.X), Forms.ConvertToScaledPixel(bezierSegment.Point1.Y), Forms.ConvertToScaledPixel(bezierSegment.Point2.X), Forms.ConvertToScaledPixel(bezierSegment.Point2.Y)); lastPoint = bezierSegment.Point2; } // PolyQuadraticBezierSegment else if (pathSegment is PolyQuadraticBezierSegment) { PolyQuadraticBezierSegment polyBezierSegment = pathSegment as PolyQuadraticBezierSegment; PointCollection points = polyBezierSegment.Points; for (int i = 0; i < points.Count; i += 2) { path.QuadTo( Forms.ConvertToScaledPixel(points[i + 0].X), Forms.ConvertToScaledPixel(points[i + 0].Y), Forms.ConvertToScaledPixel(points[i + 1].X), Forms.ConvertToScaledPixel(points[i + 1].Y)); } lastPoint = points[points.Count - 1]; } // ArcSegment else if (pathSegment is ArcSegment) { ArcSegment arcSegment = pathSegment as ArcSegment; List <Point> points = new List <Point>(); GeometryHelper.FlattenArc(points, lastPoint, arcSegment.Point, arcSegment.Size.Width, arcSegment.Size.Height, arcSegment.RotationAngle, arcSegment.IsLargeArc, arcSegment.SweepDirection == SweepDirection.CounterClockwise, 1); for (int i = 0; i < points.Count; i++) { path.LineTo( Forms.ConvertToScaledPixel(points[i].X), Forms.ConvertToScaledPixel(points[i].Y)); } if (points.Count > 0) { lastPoint = points[points.Count - 1]; } } } if (pathFigure.IsClosed) { path.Close(); } } return(path); }
private IRenderingElement GenerateSgroupBrackets(Sgroup sgroup, IList <SgroupBracket> brackets, IReadOnlyDictionary <IAtom, AtomSymbol> symbols, string subscriptSuffix, string superscriptSuffix) { // brackets are square by default (style:0) var style = (int?)sgroup.GetValue(SgroupKey.CtabBracketStyle); bool round = style != null && style == 1; ElementGroup result = new ElementGroup(); var atoms = sgroup.Atoms; var crossingBonds = sgroup.Bonds; // easy to depict in correct orientation, we just // point each bracket at the atom of a crossing // bond that is 'in' the group - this scales // to more than two brackets // first we need to pair the brackets with the bonds var pairs = crossingBonds.Count == brackets.Count ? BracketBondPairs(brackets, crossingBonds) : Dictionaries.Empty <SgroupBracket, IBond>(); // override bracket layout around single atoms to bring them in closer if (atoms.Count == 1) { IAtom atom = atoms.First(); // e.g. 2 HCL, 8 H2O etc. if (IsUnsignedInt(subscriptSuffix) && !crossingBonds.Any() && symbols.ContainsKey(atom)) { TextOutline prefix = new TextOutline('·' + subscriptSuffix, font, emSize).Resize(1 / scale, 1 / -scale); Rect prefixBounds = prefix.LogicalBounds; AtomSymbol symbol = symbols[atom]; Rect bounds = symbol.GetConvexHull().Outline.Bounds; // make slightly large bounds = new Rect(bounds.Bottom - 2 * stroke, bounds.Left - 2 * stroke, bounds.Width + 4 * stroke, bounds.Height + 4 * stroke); prefix = prefix.Translate(bounds.Bottom - prefixBounds.Top, symbol.GetAlignmentCenter().Y - prefixBounds.CenterY()); result.Add(GeneralPath.ShapeOf(prefix.GetOutline(), foreground)); } // e.g. CC(O)nCC else if (crossingBonds.Count > 0) { double scriptscale = labelScale; TextOutline leftBracket = new TextOutline("(", font, emSize).Resize(1 / scale, 1 / -scale); TextOutline rightBracket = new TextOutline(")", font, emSize).Resize(1 / scale, 1 / -scale); var leftCenter = leftBracket.GetCenter(); var rightCenter = rightBracket.GetCenter(); if (symbols.ContainsKey(atom)) { AtomSymbol symbol = symbols[atom]; var bounds = symbol.GetConvexHull().Outline.Bounds; // make slightly large bounds = new Rect(bounds.Left - 2 * stroke, bounds.Top - 2 * stroke, bounds.Width + 4 * stroke, bounds.Height + 4 * stroke); leftBracket = leftBracket.Translate(bounds.Left - 0.1 - leftCenter.X, symbol.GetAlignmentCenter().Y - leftCenter.Y); rightBracket = rightBracket.Translate(bounds.Right + 0.1 - rightCenter.X, symbol.GetAlignmentCenter().Y - rightCenter.Y); } else { Vector2 p = atoms.First().Point2D.Value; leftBracket = leftBracket.Translate(p.X - 0.2 - leftCenter.X, p.Y - leftCenter.Y); rightBracket = rightBracket.Translate(p.X + 0.2 - rightCenter.X, p.Y - rightCenter.Y); } result.Add(GeneralPath.ShapeOf(leftBracket.GetOutline(), foreground)); result.Add(GeneralPath.ShapeOf(rightBracket.GetOutline(), foreground)); var rightBracketBounds = rightBracket.GetBounds(); // subscript/superscript suffix annotation if (subscriptSuffix != null && subscriptSuffix.Any()) { TextOutline subscriptOutline = LeftAlign(MakeText(subscriptSuffix.ToLowerInvariant(), new Vector2(rightBracketBounds.Right, rightBracketBounds.Top - 0.1), new Vector2(-0.5 * rightBracketBounds.Width, 0), scriptscale)); result.Add(GeneralPath.ShapeOf(subscriptOutline.GetOutline(), foreground)); } if (superscriptSuffix != null && superscriptSuffix.Any()) { TextOutline superscriptOutline = LeftAlign(MakeText(superscriptSuffix.ToLowerInvariant(), new Vector2(rightBracketBounds.Right, rightBracketBounds.Bottom + 0.1), new Vector2(-rightBracketBounds.Width, 0), scriptscale)); result.Add(GeneralPath.ShapeOf(superscriptOutline.GetOutline(), foreground)); } } } else if (pairs.Any()) { SgroupBracket suffixBracket = null; Vector2? suffixBracketPerp = null; foreach (var e in pairs) { var bracket = e.Key; var bond = e.Value; var inGroupAtom = atoms.Contains(bond.Begin) ? bond.Begin : bond.End; var p1 = bracket.FirstPoint; var p2 = bracket.SecondPoint; var perp = VecmathUtil.NewPerpendicularVector(VecmathUtil.NewUnitVector(p1, p2)); // point the vector at the atom group Vector2 midpoint = VecmathUtil.Midpoint(p1, p2); if (Vector2.Dot(perp, VecmathUtil.NewUnitVector(midpoint, inGroupAtom.Point2D.Value)) < 0) { perp = Vector2.Negate(perp); } perp *= bracketDepth; if (round) { result.Add(CreateRoundBracket(p1, p2, perp, midpoint)); } else { result.Add(CreateSquareBracket(p1, p2, perp)); } if (suffixBracket == null) { suffixBracket = bracket; suffixBracketPerp = perp; } else { // is this bracket better as a suffix? Vector2 sp1 = suffixBracket.FirstPoint; Vector2 sp2 = suffixBracket.SecondPoint; double bestMaxX = Math.Max(sp1.X, sp2.X); double thisMaxX = Math.Max(p1.X, p2.X); double bestMaxY = Math.Max(sp1.Y, sp2.Y); double thisMaxY = Math.Max(p1.Y, p2.Y); // choose the most eastern or.. the most southern double xDiff = thisMaxX - bestMaxX; double yDiff = thisMaxY - bestMaxY; if (xDiff > EQUIV_THRESHOLD || (xDiff > -EQUIV_THRESHOLD && yDiff < -EQUIV_THRESHOLD)) { suffixBracket = bracket; suffixBracketPerp = perp; } } } // write the labels if (suffixBracket != null) { Vector2 subSufPnt = suffixBracket.FirstPoint; Vector2 supSufPnt = suffixBracket.SecondPoint; // try to put the subscript on the bottom double xDiff = subSufPnt.X - supSufPnt.X; double yDiff = subSufPnt.Y - supSufPnt.Y; if (yDiff > EQUIV_THRESHOLD || (yDiff > -EQUIV_THRESHOLD && xDiff > EQUIV_THRESHOLD)) { Vector2 tmpP = subSufPnt; subSufPnt = supSufPnt; supSufPnt = tmpP; } // subscript/superscript suffix annotation if (subscriptSuffix != null && subscriptSuffix.Any()) { TextOutline subscriptOutline = LeftAlign(MakeText(subscriptSuffix.ToLowerInvariant(), subSufPnt, suffixBracketPerp.Value, labelScale)); result.Add(GeneralPath.ShapeOf(subscriptOutline.GetOutline(), foreground)); } if (superscriptSuffix != null && superscriptSuffix.Any()) { TextOutline superscriptOutline = LeftAlign(MakeText(superscriptSuffix.ToLowerInvariant(), supSufPnt, suffixBracketPerp.Value, labelScale)); result.Add(GeneralPath.ShapeOf(superscriptOutline.GetOutline(), foreground)); } } } else if (brackets.Count == 2) { var b1p1 = brackets[0].FirstPoint; var b1p2 = brackets[0].SecondPoint; var b2p1 = brackets[1].FirstPoint; var b2p2 = brackets[1].SecondPoint; var b1vec = VecmathUtil.NewUnitVector(b1p1, b1p2); var b2vec = VecmathUtil.NewUnitVector(b2p1, b2p2); var b1pvec = VecmathUtil.NewPerpendicularVector(b1vec); var b2pvec = VecmathUtil.NewPerpendicularVector(b2vec); // Point the vectors at each other if (Vector2.Dot(b1pvec, VecmathUtil.NewUnitVector(b1p1, b2p1)) < 0) { b1pvec = Vector2.Negate(b1pvec); } if (Vector2.Dot(b2pvec, VecmathUtil.NewUnitVector(b2p1, b1p1)) < 0) { b2pvec = Vector2.Negate(b2pvec); } // scale perpendicular vectors by how deep the brackets need to be b1pvec *= bracketDepth; b2pvec *= bracketDepth; // bad brackets if (double.IsNaN(b1pvec.X) || double.IsNaN(b1pvec.Y) || double.IsNaN(b2pvec.X) || double.IsNaN(b2pvec.Y)) { return(result); } { var path = new PathGeometry(); if (round) { { // bracket 1 (cp: control point) var pf = new PathFigure { StartPoint = new Point(b1p1.X + b1pvec.X, b1p1.Y + b1pvec.Y) }; Vector2 cpb1 = VecmathUtil.Midpoint(b1p1, b1p2); cpb1 += VecmathUtil.Negate(b1pvec); var seg = new QuadraticBezierSegment { Point1 = new Point(cpb1.X, cpb1.Y), Point2 = new Point(b1p2.X + b1pvec.X, b1p2.Y + b1pvec.Y) }; pf.Segments.Add(seg); path.Figures.Add(pf); } { // bracket 2 (cp: control point) var pf = new PathFigure { StartPoint = new Point(b2p1.X + b2pvec.X, b2p1.Y + b2pvec.Y) }; Vector2 cpb2 = VecmathUtil.Midpoint(b2p1, b2p2); cpb2 += VecmathUtil.Negate(b2pvec); var seg = new QuadraticBezierSegment { Point1 = new Point(cpb2.X, cpb2.Y), Point2 = new Point(b2p2.X + b2pvec.X, b2p2.Y + b2pvec.Y) }; pf.Segments.Add(seg); path.Figures.Add(pf); } } else { { // bracket 1 var pf = new PathFigure { StartPoint = new Point(b1p1.X + b1pvec.X, b1p1.Y + b1pvec.Y) }; var seg = new PolyLineSegment(); seg.Points.Add(new Point(b1p1.X, b1p1.Y)); seg.Points.Add(new Point(b1p2.X, b1p2.Y)); seg.Points.Add(new Point(b1p2.X + b1pvec.X, b1p2.Y + b1pvec.Y)); pf.Segments.Add(seg); path.Figures.Add(pf); } { // bracket 2 var pf = new PathFigure { StartPoint = new Point(b2p1.X + b2pvec.X, b2p1.Y + b2pvec.Y) }; var seg = new PolyLineSegment(); seg.Points.Add(new Point(b2p1.X, b2p1.Y)); seg.Points.Add(new Point(b2p2.X, b2p2.Y)); seg.Points.Add(new Point(b2p2.X + b2pvec.X, b2p2.Y + b2pvec.Y)); pf.Segments.Add(seg); path.Figures.Add(pf); } } result.Add(GeneralPath.OutlineOf(path, stroke, foreground)); } // work out where to put the suffix labels (e.g. ht/hh/eu) superscript // and (e.g. n, xl, c, mix) subscript // TODO: could be improved double b1MaxX = Math.Max(b1p1.X, b1p2.X); double b2MaxX = Math.Max(b2p1.X, b2p2.X); double b1MaxY = Math.Max(b1p1.Y, b1p2.Y); double b2MaxY = Math.Max(b2p1.Y, b2p2.Y); Vector2 subSufPnt = b2p2; Vector2 supSufPnt = b2p1; Vector2 subpvec = b2pvec; double bXDiff = b1MaxX - b2MaxX; double bYDiff = b1MaxY - b2MaxY; if (bXDiff > EQUIV_THRESHOLD || (bXDiff > -EQUIV_THRESHOLD && bYDiff < -EQUIV_THRESHOLD)) { subSufPnt = b1p2; supSufPnt = b1p1; subpvec = b1pvec; } double xDiff = subSufPnt.X - supSufPnt.X; double yDiff = subSufPnt.Y - supSufPnt.Y; if (yDiff > EQUIV_THRESHOLD || (yDiff > -EQUIV_THRESHOLD && xDiff > EQUIV_THRESHOLD)) { Vector2 tmpP = subSufPnt; subSufPnt = supSufPnt; supSufPnt = tmpP; } // subscript/superscript suffix annotation if (subscriptSuffix != null && subscriptSuffix.Any()) { TextOutline subscriptOutline = LeftAlign(MakeText(subscriptSuffix.ToLowerInvariant(), subSufPnt, subpvec, labelScale)); result.Add(GeneralPath.ShapeOf(subscriptOutline.GetOutline(), foreground)); } if (superscriptSuffix != null && superscriptSuffix.Any()) { TextOutline superscriptOutline = LeftAlign(MakeText(superscriptSuffix.ToLowerInvariant(), supSufPnt, subpvec, labelScale)); result.Add(GeneralPath.ShapeOf(superscriptOutline.GetOutline(), foreground)); } } return(result); }
Visual CreateQuadraticBezierSegments() { DrawingContext dc; DrawingVisual dv = PrepareDrawingVisual(out dc); Point startPoint = new Point(20, 120); Point[] points = { new Point(30, 20), new Point(150, 130), new Point(200, 20), new Point(215, 60) }; PathGeometry path; PathFigure figure; Brush brush = Brushes.DarkOrange; Pen pen = new Pen(Brushes.DarkBlue, 3); BeginBox(dc, 1, BoxOptions.Tile, "stroke"); path = new PathGeometry(); path.Figures.Add(figure = new PathFigure()); figure.StartPoint = startPoint; figure.Segments.Add(new PolyQuadraticBezierSegment(points, true)); dc.DrawGeometry(null, pen, path); EndBox(dc); BeginBox(dc, 2, BoxOptions.Tile, "stroke, figure closed"); path = new PathGeometry(); path.Figures.Add(figure = new PathFigure()); figure.StartPoint = startPoint; figure.IsClosed = true; figure.Segments.Add(new PolyQuadraticBezierSegment(points, true)); dc.DrawGeometry(null, pen, path); EndBox(dc); BeginBox(dc, 3, BoxOptions.Tile, "fill"); path = new PathGeometry(); path.Figures.Add(figure = new PathFigure()); figure.StartPoint = startPoint; figure.Segments.Add(new PolyQuadraticBezierSegment(points, true)); dc.DrawGeometry(brush, null, path); EndBox(dc); BeginBox(dc, 4, BoxOptions.Tile, "fill, figure closed"); path = new PathGeometry(); path.Figures.Add(figure = new PathFigure()); figure.StartPoint = startPoint; figure.IsClosed = true; figure.Segments.Add(new PolyQuadraticBezierSegment(points, true)); dc.DrawGeometry(brush, null, path); EndBox(dc); BeginBox(dc, 5, BoxOptions.Tile, "fill & stroke"); path = new PathGeometry(); path.Figures.Add(figure = new PathFigure()); figure.StartPoint = startPoint; figure.Segments.Add(new PolyQuadraticBezierSegment(points, true)); dc.DrawGeometry(brush, pen, path); EndBox(dc); BeginBox(dc, 6, BoxOptions.Tile, "fill & stroke, figure closed"); path = new PathGeometry(); path.Figures.Add(figure = new PathFigure()); figure.StartPoint = startPoint; figure.IsClosed = true; figure.Segments.Add(new PolyQuadraticBezierSegment(points, true)); dc.DrawGeometry(brush, pen, path); EndBox(dc); //BeginBox(dc, 7); //EndBox(dc); //BeginBox(dc, 8); //EndBox(dc); dc.Close(); return(dv); }
//------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Render override to render the composition adorner here. /// </summary> protected override void OnRender(DrawingContext drawingContext) { // Get the matrix from AdornedElement to the visual parent to get the transformed // start/end point Visual parent2d = VisualTreeHelper.GetParent(this.AdornedElement) as Visual; if (parent2d == null) { return; } GeneralTransform transform = AdornedElement.TransformToAncestor(parent2d); if (transform == null) { return; } // Please note that we do the highlight adornment for the CONVERTED text only // for Simplified Chinese IMEs. Doing this uniformly across all IMEs wasnt possible // because it was noted that some of them (viz. Japanese) werent being consistent // about this attribute. bool isChinesePinyin = chinesePinyin.Equals(InputLanguageManager.Current.CurrentInputLanguage.IetfLanguageTag); // Render the each of the composition string attribute from the attribute ranges. for (int i = 0; i < _attributeRanges.Count; i++) { DoubleCollection dashArray; // Get the composition attribute range from the attribute range lists AttributeRange attributeRange = (AttributeRange)_attributeRanges[i]; // Skip the rendering composition lines if the composition line doesn't exist. if (attributeRange.CompositionLines.Count == 0) { continue; } // Set the line bold and squiggle bool lineBold = attributeRange.TextServicesDisplayAttribute.IsBoldLine ? true : false; bool squiggle = false; bool hasVirtualSelection = (attributeRange.TextServicesDisplayAttribute.AttrInfo & UnsafeNativeMethods.TF_DA_ATTR_INFO.TF_ATTR_TARGET_CONVERTED) != 0; Brush selectionBrush = null; double selectionOpacity = -1; Pen selectionPen = null; if (isChinesePinyin && hasVirtualSelection) { DependencyObject owner = _textView.TextContainer.Parent; selectionBrush = (Brush)owner.GetValue(TextBoxBase.SelectionBrushProperty); selectionOpacity = (double)owner.GetValue(TextBoxBase.SelectionOpacityProperty); } // Set the line height and cluse gap value that base on the ratio of text height double height = attributeRange.Height; double lineHeight = height * (lineBold ? BoldLineHeightRatio : NormalLineHeightRatio); double clauseGap = height * ClauseGapRatio; // Create Pen for drawing the composition lines with the specified line color Pen pen = new Pen(new SolidColorBrush(Colors.Black), lineHeight); // Set the pen style that based on IME's composition line style switch (attributeRange.TextServicesDisplayAttribute.LineStyle) { case UnsafeNativeMethods.TF_DA_LINESTYLE.TF_LS_DOT: // Add the dot length and specify the start/end line cap as the round dashArray = new DoubleCollection(); dashArray.Add(DotLength); dashArray.Add(DotLength); pen.DashStyle = new DashStyle(dashArray, 0); pen.DashCap = System.Windows.Media.PenLineCap.Round; pen.StartLineCap = System.Windows.Media.PenLineCap.Round; pen.EndLineCap = System.Windows.Media.PenLineCap.Round; // Update the line height for the dot line. Dot line will be more thickness than // other line to show it clearly. lineHeight = height * (lineBold ? BoldDotLineHeightRatio : NormalDotLineHeightRatio); break; case UnsafeNativeMethods.TF_DA_LINESTYLE.TF_LS_DASH: double dashLength = height * (lineBold ? BoldDashRatio : NormalDashRatio); double dashGapLength = height * (lineBold ? BoldDashGapRatio : NormalDashGapRatio); // Add the dash and dash gap legth dashArray = new DoubleCollection(); dashArray.Add(dashLength); dashArray.Add(dashGapLength); pen.DashStyle = new DashStyle(dashArray, 0); pen.DashCap = System.Windows.Media.PenLineCap.Round; pen.StartLineCap = System.Windows.Media.PenLineCap.Round; pen.EndLineCap = System.Windows.Media.PenLineCap.Round; break; case UnsafeNativeMethods.TF_DA_LINESTYLE.TF_LS_SOLID: pen.StartLineCap = System.Windows.Media.PenLineCap.Round; pen.EndLineCap = System.Windows.Media.PenLineCap.Round; break; case UnsafeNativeMethods.TF_DA_LINESTYLE.TF_LS_SQUIGGLE: squiggle = true; break; } double halfLineHeight = lineHeight / 2; // Draw the each of the composition line for (int j = 0; j < attributeRange.CompositionLines.Count; j++) { CompositionLine compositionLine = (CompositionLine)attributeRange.CompositionLines[j]; // Get the start/end point for composition adorner. // Currently Text doesn't aware of the spaceroom for the drawing of the composition // adorner(like as normal/bold dot/line/squggle), so we should draw the composition adorners // to the closest area of the bottom text. Point startPoint = new Point(compositionLine.StartPoint.X + clauseGap, compositionLine.StartPoint.Y - halfLineHeight); Point endPoint = new Point(compositionLine.EndPoint.X - clauseGap, compositionLine.EndPoint.Y - halfLineHeight); // Apply composition line color which is actually the foreground of text as well pen.Brush = new SolidColorBrush(compositionLine.LineColor); // Apply matrix to start/end point // REVIEW: if the points can't be transformed, should we not draw anything? transform.TryTransform(startPoint, out startPoint); transform.TryTransform(endPoint, out endPoint); if (isChinesePinyin && hasVirtualSelection) { Rect rect = Rect.Union(compositionLine.StartRect, compositionLine.EndRect); rect = transform.TransformBounds(rect); drawingContext.PushOpacity(selectionOpacity); drawingContext.DrawRectangle(selectionBrush, selectionPen, rect); drawingContext.Pop(); } if (squiggle) { // Draw the squiggle line with using of the PathFigure and DrawGemetry. // We may revisit this logic to render the smooth squiggle line. Point pathPoint = new Point(startPoint.X, startPoint.Y - halfLineHeight); double squiggleGap = halfLineHeight; PathFigure pathFigure = new PathFigure(); pathFigure.StartPoint = pathPoint; int indexPoint = 0; while (indexPoint < ((endPoint.X - startPoint.X) / (squiggleGap))) { if (indexPoint % 4 == 0 || indexPoint % 4 == 3) { pathPoint = new Point(pathPoint.X + squiggleGap, pathPoint.Y + halfLineHeight); pathFigure.Segments.Add(new LineSegment(pathPoint, true)); } else if (indexPoint % 4 == 1 || indexPoint % 4 == 2) { pathPoint = new Point(pathPoint.X + squiggleGap, pathPoint.Y - halfLineHeight); pathFigure.Segments.Add(new LineSegment(pathPoint, true)); } indexPoint++; } PathGeometry pathGeometry = new PathGeometry(); pathGeometry.Figures.Add(pathFigure); // Draw the composition line with the squiggle drawingContext.DrawGeometry(null, pen, pathGeometry); } else { drawingContext.DrawLine(pen, startPoint, endPoint); } } } }
/// <summary> /// Fills a Polygon. /// </summary> /// <param name="color">The Color.</param> /// <param name="polygon">The Polygon.</param> public void FillPolygon(Color color, Polygon polygon) { var geometry = new PathGeometry(DirectXHelper.Direct2DFactory); using (GeometrySink sink = geometry.Open()) { sink.BeginFigure(DirectXHelper.ConvertVector(polygon.Points[0]), FigureBegin.Filled); for (int i = 1; i < polygon.Points.Length; i++) sink.AddLine(DirectXHelper.ConvertVector(polygon.Points[i])); sink.EndFigure(FigureEnd.Closed); sink.Close(); _renderTarget.FillGeometry(geometry, new SolidColorBrush(DirectXHelper.RenderTarget, DirectXHelper.ConvertColor(color))); } geometry.Dispose(); }
public SizeAnimationExample() { // Create a NameScope for this page so that // Storyboards can be used. NameScope.SetNameScope(this, new NameScope()); // Create an ArcSegment to define the geometry of the path. // The Size property of this segment is animated. ArcSegment myArcSegment = new ArcSegment(); myArcSegment.Size = new Size(90, 80); myArcSegment.SweepDirection = SweepDirection.Clockwise; myArcSegment.Point = new Point(500, 200); // Assign the segment a name so that // it can be targeted by a Storyboard. this.RegisterName( "myArcSegment", myArcSegment); PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection(); myPathSegmentCollection.Add(myArcSegment); // Create a PathFigure to be used for the PathGeometry of myPath. PathFigure myPathFigure = new PathFigure(); // Set the starting point for the PathFigure specifying that the // geometry starts at point 100,200. myPathFigure.StartPoint = new Point(100, 200); myPathFigure.Segments = myPathSegmentCollection; PathFigureCollection myPathFigureCollection = new PathFigureCollection(); myPathFigureCollection.Add(myPathFigure); PathGeometry myPathGeometry = new PathGeometry(); myPathGeometry.Figures = myPathFigureCollection; // Create a path to draw a geometry with. Path myPath = new Path(); myPath.Stroke = Brushes.Black; myPath.StrokeThickness = 1; // specify the shape of the path using the path geometry. myPath.Data = myPathGeometry; SizeAnimation mySizeAnimation = new SizeAnimation(); mySizeAnimation.Duration = TimeSpan.FromSeconds(2); // Set the animation to repeat forever. mySizeAnimation.RepeatBehavior = RepeatBehavior.Forever; // Set the From and To properties of the animation. mySizeAnimation.From = new Size(90, 80); mySizeAnimation.To = new Size(200, 200); // Set the animation to target the Size property // of the object named "myArcSegment." Storyboard.SetTargetName(mySizeAnimation, "myArcSegment"); Storyboard.SetTargetProperty( mySizeAnimation, new PropertyPath(ArcSegment.SizeProperty)); // Create a storyboard to apply the animation. Storyboard ellipseStoryboard = new Storyboard(); ellipseStoryboard.Children.Add(mySizeAnimation); // Start the storyboard when the Path loads. myPath.Loaded += delegate(object sender, RoutedEventArgs e) { ellipseStoryboard.Begin(this); }; Canvas containerCanvas = new Canvas(); containerCanvas.Children.Add(myPath); Content = containerCanvas; }
protected override void OnRender(DrawingContext drawingContext) { Rect fullRect = new Rect(new Point(), new Size(ActualWidth, ActualHeight)); drawingContext.PushClip(new RectangleGeometry(fullRect)); drawingContext.DrawRectangle(Background, null, fullRect); Pen linePen = new Pen(Brushes.White, 3); //drawingContext.DrawLine(linePen, new Point(0, ActualHeight / 2), new Point(ActualWidth, ActualHeight / 2)); drawingContext.DrawLine(new Pen(Brushes.Red, 11), new Point(Midpoint * ActualWidth, 0), new Point(Midpoint * ActualWidth, ActualHeight)); if (Timeline != null) { double timeFrom = _progress - Midpoint * TotalDisplayedDuration; double timeTo = _progress + (1 - Midpoint) * TotalDisplayedDuration; double position = Math.Floor(timeFrom); List <double> beatPositions = new List <double>(); while (position < timeTo) { BeatGroup group = Timeline.FindActiveGroup(position); if (group == null) { group = Timeline.FindNextGroup(position); if (group != null) { position = group.Start; } } if (group == null) { break; } position = group.FindStartingPoint(position); while (position < group.End && position < timeTo) { foreach (double beat in group.Pattern.BeatPositions) { double relativePosition = (((beat * group.ActualPatternDuration) + position - timeFrom) / (timeTo - timeFrom)); beatPositions.Add(relativePosition); } position += group.ActualPatternDuration; } } const double safeSpace = 30; double y = ActualHeight / 2.0; if (_simpleRendering) { DrawLine(drawingContext, Colors.Red, new Point(-safeSpace, y), new Point(ActualWidth + safeSpace, y)); foreach (double pos in beatPositions) { DrawLine(drawingContext, Colors.Lime, new Point(pos * ActualWidth, -5), new Point(pos * ActualWidth, ActualHeight + 5)); } } else { PathGeometry geometry = new PathGeometry(); if (beatPositions.Count > 0) { double start = Math.Min(0, beatPositions.First()); double end = Math.Max(1, beatPositions.Last()); PathFigure figure = new PathFigure { StartPoint = new Point(start * ActualWidth - safeSpace, y) }; geometry.Figures.Add(figure); foreach (double beatPosition in beatPositions) { AppendSwiggely(figure, new Point(beatPosition * ActualWidth, y)); } figure.Segments.Add(new LineSegment(new Point(end * ActualWidth + safeSpace, y), true)); } else { geometry.Figures.Add(new PathFigure(new Point(-safeSpace, y), new[] { new LineSegment(new Point(ActualWidth + safeSpace, y), true) }, false)); } drawingContext.DrawGeometry(null, new Pen(new SolidColorBrush(Colors.Red) { Opacity = 0.5 }, 4) { LineJoin = PenLineJoin.Round }, geometry); drawingContext.DrawGeometry(null, new Pen(new SolidColorBrush(Colors.White) { Opacity = 1.0 }, 2) { LineJoin = PenLineJoin.Round }, geometry); } } drawingContext.Pop(); }
private void AddGeometry(StringBuilder svgString, PathGeometry path) { svgString.Append("<path d=\""); foreach (PathFigure pf in path.Figures) { svgString.Append("M "); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", pf.StartPoint.X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", pf.StartPoint.Y); foreach (PathSegment ps in pf.Segments) { if (ps is PolyLineSegment plSeg) { for (int i = 0; i < plSeg.Points.Count; ++i) { svgString.Append("L "); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", plSeg.Points[i].X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", plSeg.Points[i].Y); } } else if (ps is PolyBezierSegment pbSeg) { for (int i = 0; i < pbSeg.Points.Count; i += 3) { svgString.Append("C "); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", pbSeg.Points[i].X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", pbSeg.Points[i].Y); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", pbSeg.Points[i + 1].X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", pbSeg.Points[i + 1].Y); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", pbSeg.Points[i + 2].X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", pbSeg.Points[i + 2].Y); } } else if (ps is LineSegment lSeg) { svgString.Append("L "); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", lSeg.Point.X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", lSeg.Point.Y); } else if (ps is BezierSegment bSeg) { svgString.Append("C "); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", bSeg.Point1.X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", bSeg.Point1.Y); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", bSeg.Point2.X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", bSeg.Point2.Y); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", bSeg.Point3.X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", bSeg.Point3.Y); } else if (ps is QuadraticBezierSegment qbSeg) { //Untested: BuildGeometry converts quadratic bezier to cubic svgString.Append("Q "); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", qbSeg.Point1.X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", qbSeg.Point1.Y); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", qbSeg.Point2.X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", qbSeg.Point2.Y); } else if (ps is PolyQuadraticBezierSegment pqbSeg) { //Untested: BuildGeometry converts quadratic bezier to cubic for (int i = 0; i < pqbSeg.Points.Count; i += 2) { svgString.Append("Q "); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", pqbSeg.Points[i].X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", pqbSeg.Points[i].Y); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", pqbSeg.Points[i + 1].X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", pqbSeg.Points[i + 1].Y); } } else { Debug.Assert(false); //If asserted, implement segment type } } if (pf.IsClosed) { svgString.Append("Z "); } } svgString.Append("\" fill = \"black\" />"); svgString.Append(Environment.NewLine); }
public MainWindow() { InitializeComponent(); // Create a set of known points. var keyPoints = new CumulativeKeyPointCollection <Point, double>( new PointInterpolationProvider() ) { new Point(50, 50), new Point(100, 100), new Point(100, 200), new Point(300, 20), new Point(350, 140), new Point(60, 300), new Point(300, 250), new Point(300, 330) }; AbstractInterpolation <Point, double> interpolation = new CardinalSplineInterpolation <Point, double>(keyPoints); // Create a set of interpolated points between the known points. var interpolatedPoints = new List <Point>(); double curPercentage = 0; while (curPercentage < 1) { interpolatedPoints.Add(interpolation.Interpolate(curPercentage)); curPercentage += 0.001; } // Create line segments. IEnumerable <LineSegment> lines = interpolatedPoints.Select(p => new LineSegment(p, true)); // Create graph. var graphFigure = new PathFigure(keyPoints[0], lines, false); var graphGeometry = new PathGeometry(new List <PathFigure> { graphFigure }); var graph = new Path { Stroke = Brushes.Black, Data = graphGeometry }; DrawCanvas.Children.Add(graph); // Create points. const double pointSize = 5; foreach (var p in keyPoints) { var rect = new Rectangle { Width = pointSize, Height = pointSize, Fill = Brushes.Red }; Canvas.SetLeft(rect, p.X - pointSize / 2); Canvas.SetTop(rect, p.Y - pointSize / 2); DrawCanvas.Children.Add(rect); } // Draw tangent at a desired location. const double tangentAtPercentage = 0.95; const double tangentLenght = 100; Point startTangent = interpolation.Interpolate(tangentAtPercentage); Point tangent = interpolation.TangentAt(tangentAtPercentage); var normalized = new Vector3D(tangent.X, tangent.Y, 0); normalized.Normalize(); tangent = new Point(normalized.X, normalized.Y); var tangentLine = new Line { X1 = startTangent.X, Y1 = startTangent.Y, X2 = startTangent.X + tangent.X * tangentLenght, Y2 = startTangent.Y + tangent.Y * tangentLenght, Stroke = Brushes.Blue }; DrawCanvas.Children.Add(tangentLine); }
/// <summary> /// Returns the head of an arrow /// </summary> /// <param name="line">PathFigure describing the body of the arrow</param> /// <param name="reverse">Draw arrow head at start instead of end of arrow</param> /// <returns>Simple path figure of arrow head, oriented appropriately </returns> public PathFigure ArrowHeadGeometry(PathFigure line, bool reverse = false) { Matrix matx = new Matrix(); //work out how far back the arrowhead extends double offset = ArrowHeadLength * Math.Cos(HeadAngle); var length = GetPathFigureLength(line); double progress = reverse ? (offset / length) : 1.0 - (offset / length); //if we're going for the start or end of line //Vector headVector = pt1 - pt2; //create a simple geometry so we can use a wpf trick to determine the length PathGeometry tempPG = new PathGeometry(); tempPG.Figures.Add(line); Point tempPoint, tangent; //this is a really cool method to get the angle at the end of a line of any shape. //we need to get the actual angle at the very point the arrow line enters the head tempPG.GetPointAtFractionLength(progress, out Point garbage, out tangent); //and then the very last point on the line if (reverse) { tempPG.GetPointAtFractionLength(0.0, out tempPoint, out garbage); } else { tempPG.GetPointAtFractionLength(1.0, out tempPoint, out garbage); } //chuck away the pathgeometry tempPG = null; //the tangent is an X & Y coordinate that can be converted into a vector Vector headVector = new Vector(tangent.X, tangent.Y); //normalize the vector headVector.Normalize(); //and invert it headVector *= -ArrowHeadLength; LineSegment lineseg = line.Segments[0] as LineSegment; PolyLineSegment polyseg = new PolyLineSegment(); if (!IsArrowClosed) { polyseg.Points.Clear(); matx.Rotate(HeadAngle / 2); var pointa = tempPoint + headVector * matx; polyseg.Points.Add(pointa); polyseg.Points.Add(tempPoint); matx.Rotate(-HeadAngle); var pointb = tempPoint + headVector * matx; polyseg.Points.Add(pointb); PathSegmentCollection psc = new PathSegmentCollection(); psc.Add(polyseg); PathFigure pathfig = new PathFigure(tempPoint, psc, true); return(pathfig); } else { polyseg.Points.Clear(); polyseg.Points.Add(tempPoint); matx.Rotate(HeadAngle / 2); var pointa = tempPoint + headVector * matx; polyseg.Points.Add(pointa); matx.Rotate(-HeadAngle); var pointb = tempPoint + headVector * matx; polyseg.Points.Add(pointb); PathSegmentCollection psc = new PathSegmentCollection(); psc.Add(polyseg); PathFigure pathfig = new PathFigure(tempPoint, psc, true); return(pathfig); } }
internal CurvyTab(CurvyTabVisual parentVisual, string displayText, UIElement visual) { this.Visual = visual; this.displayText = displayText; this.parentVisual = parentVisual; tabOuterPath = new PathGeometry(); tabOuterPath.Transform = new TranslateTransform(0, 0); tabInnerPath = new PathGeometry(); tabInnerPath.Transform = new TranslateTransform(0, 0); ResizeTab(); }
private IEnumerable <UIElement> CreateSegmentLines(int index, MSize offset, bool drawMidPoint = true) { var segments = _segmentLayers.SelectMany( cl => cl.Value.Paths.SelectMany(p => p.Segments.Select(s => new { Color = cl.Key, Segment = s }))) .ToList(); var segmentAndColor = segments[index]; var segment = segmentAndColor.Segment; var color = segmentAndColor.Color.Color; var regularBrush = new SolidColorBrush(MColor.FromArgb(color.A, color.R, color.G, color.B)); var points = segment is SplineSegment ? new[] { segment.Start, ((SplineSegment)segment).Mid, segment.End } : new[] { segment.Start, segment.End }; var multiplier = 10.0; var lines = new List <UIElement>(); Func <Point <double>, Point <double> > scale = p => new Point <double> { X = p.X * multiplier + offset.Width, Y = p.Y * multiplier + offset.Height }; var scaledPoints = points.Select(p => scale(p)).ToList(); var brush = regularBrush; if (segment is LineSegment) { //http://stackoverflow.com/questions/1624341/getting-pair-set-using-linq var groupedPoints = scaledPoints.Select((p, i) => new { First = p, Second = scaledPoints[i == scaledPoints.Count - 1 ? 0 : i + 1] }); foreach (var point in groupedPoints) { lines.Add(CreateLineDot(point.First, brush)); lines.Add(CreateLine(point.First, point.Second, brush, false)); } } //http://stackoverflow.com/a/21958079/294804 //http://stackoverflow.com/a/5336694/294804 if (segment is SplineSegment) { lines.Add(CreateLineDot(scaledPoints[0], brush)); //http://stackoverflow.com/questions/13940983/how-to-draw-bezier-curve-by-several-points var b = Bezier.GetBezierApproximation(scaledPoints.Select(p => new System.Windows.Point(p.X, p.Y)).ToArray(), 256); PathFigure pf = new PathFigure(b.Points[0], new[] { b }, false); PathFigureCollection pfc = new PathFigureCollection(); pfc.Add(pf); var pge = new PathGeometry { Figures = pfc }; System.Windows.Shapes.Path path = new System.Windows.Shapes.Path { Data = pge, Stroke = brush }; lines.Add(path); if (drawMidPoint) { lines.Add(CreateLineDot(scaledPoints[1], brush)); } lines.Add(CreateLineDot(scaledPoints[2], brush)); } return(lines); }
void CreateDeviceIndependentResources() { string msc_fontName = "Verdana"; float msc_fontSize = 50; string fps_fontName = "Courier New"; float fps_fontSize = 12; GeometrySink spSink; // Create D2D factory d2DFactory = D2DFactory.CreateFactory(D2DFactoryType.SingleThreaded); // Create WIC factory imagingFactory = ImagingFactory.Create(); // Create DWrite factory dWriteFactory = DWriteFactory.CreateFactory(); // Create DWrite text format object textFormat = dWriteFactory.CreateTextFormat( msc_fontName, msc_fontSize); textFormat.TextAlignment = Microsoft.WindowsAPICodePack.DirectX.DirectWrite.TextAlignment.Center; textFormat.ParagraphAlignment = Microsoft.WindowsAPICodePack.DirectX.DirectWrite.ParagraphAlignment.Center; // Create DWrite text format object textFormatFps = dWriteFactory.CreateTextFormat( fps_fontName, fps_fontSize); textFormatFps.TextAlignment = Microsoft.WindowsAPICodePack.DirectX.DirectWrite.TextAlignment.Leading; textFormatFps.ParagraphAlignment = Microsoft.WindowsAPICodePack.DirectX.DirectWrite.ParagraphAlignment.Near; // Create the path geometry. pathGeometry = d2DFactory.CreatePathGeometry(); // Write to the path geometry using the geometry sink. We are going to create an // hour glass. spSink = pathGeometry.Open(); spSink.SetFillMode(Microsoft.WindowsAPICodePack.DirectX.Direct2D1.FillMode.Alternate); spSink.BeginFigure( new Point2F(0, 0), FigureBegin.Filled ); spSink.AddLine(new Point2F(200, 0)); spSink.AddBezier( new BezierSegment( new Point2F(150, 50), new Point2F(150, 150), new Point2F(200, 200) )); spSink.AddLine( new Point2F(0, 200) ); spSink.AddBezier( new BezierSegment( new Point2F(50, 150), new Point2F(50, 50), new Point2F(0, 0) )); spSink.EndFigure( FigureEnd.Closed ); spSink.Close( ); }
public override void Plot(bool animate = true) { var chart = Chart as RadarChart; if (chart == null) { return; } var alpha = 360 / chart.Max.X; var pf = new PathFigure(); var segments = new PathSegmentCollection(); var l = 0d; Point?p2 = null; for (var index = 0; index <= PrimaryValues.Count; index++) { var r1 = index != PrimaryValues.Count ? chart.ToChartRadius(PrimaryValues[index]) : chart.ToChartRadius(PrimaryValues[0]); if (index == 0) { pf.StartPoint = new Point( chart.ActualWidth / 2 + Math.Sin(alpha * index * (Math.PI / 180)) * r1, chart.ActualHeight / 2 - Math.Cos(alpha * index * (Math.PI / 180)) * r1); } else { segments.Add(new LineSegment { Point = new Point { X = chart.ActualWidth / 2 + Math.Sin(alpha * index * (Math.PI / 180)) * r1, Y = chart.ActualHeight / 2 - Math.Cos(alpha * index * (Math.PI / 180)) * r1 } }); } var p1 = new Point(chart.ActualWidth / 2 + Math.Sin(alpha * index * (Math.PI / 180)) * r1, chart.ActualHeight / 2 - Math.Cos(alpha * index * (Math.PI / 180)) * r1); if (p2 != null) { l += Math.Sqrt( Math.Pow(Math.Abs(p1.X - p2.Value.X), 2) + Math.Pow(Math.Abs(p1.Y - p2.Value.Y), 2) ); } p2 = p1; if (index == PrimaryValues.Count) { continue; } if (chart.Hoverable) { var r = new Rectangle { Fill = Brushes.Transparent, Width = 40, Height = 40, StrokeThickness = 0, Stroke = Brushes.Red }; var e = new Ellipse { Width = PointRadius * 2, Height = PointRadius * 2, Fill = new SolidColorBrush { Color = Color }, Stroke = new SolidColorBrush { Color = Chart.PointHoverColor }, StrokeThickness = 2 }; r.MouseEnter += chart.OnDataMouseEnter; r.MouseLeave += chart.OnDataMouseLeave; chart.Canvas.Children.Add(r); Shapes.Add(r); chart.HoverableShapes.Add(new HoverableShape { Serie = this, Shape = r, Value = new Point(index * alpha, PrimaryValues[index]), Target = e }); Shapes.Add(e); chart.Canvas.Children.Add(e); Panel.SetZIndex(r, int.MaxValue); Canvas.SetLeft(e, p1.X - e.Width / 2); Canvas.SetTop(e, p1.Y - e.Height / 2); Panel.SetZIndex(e, 2); Canvas.SetLeft(r, p1.X - r.Width / 2); Canvas.SetTop(r, p1.Y - r.Height / 2); Panel.SetZIndex(r, int.MaxValue); if (!chart.DisableAnimation && animate) { var topAnim = new DoubleAnimation { From = chart.ActualHeight / 2, To = p1.Y - e.Height / 2, Duration = TimeSpan.FromMilliseconds(300) }; e.BeginAnimation(Canvas.TopProperty, topAnim); var leftAnim = new DoubleAnimation { From = chart.ActualWidth / 2, To = p1.X - e.Width / 2, Duration = TimeSpan.FromMilliseconds(300) }; e.BeginAnimation(Canvas.LeftProperty, leftAnim); } } } pf.Segments = segments; var g = new PathGeometry { Figures = new PathFigureCollection(new List <PathFigure> { pf }) }; var path = new Path { Stroke = new SolidColorBrush { Color = Color }, StrokeThickness = StrokeThickness, Data = g, StrokeEndLineCap = PenLineCap.Round, StrokeStartLineCap = PenLineCap.Round, Fill = new SolidColorBrush { Color = Color, Opacity = .2 }, StrokeDashOffset = l, StrokeDashArray = new DoubleCollection { l, l } }; var draw = new DoubleAnimationUsingKeyFrames { BeginTime = TimeSpan.FromSeconds(0), KeyFrames = new DoubleKeyFrameCollection { new SplineDoubleKeyFrame { KeyTime = TimeSpan.FromMilliseconds(1), Value = l }, new SplineDoubleKeyFrame { KeyTime = TimeSpan.FromMilliseconds(750), Value = 0 } } }; Storyboard.SetTarget(draw, path); Storyboard.SetTargetProperty(draw, new PropertyPath(Shape.StrokeDashOffsetProperty)); var sbDraw = new Storyboard(); sbDraw.Children.Add(draw); var animated = false; if (!chart.DisableAnimation) { if (animate) { sbDraw.Begin(); animated = true; } } if (!animated) { path.StrokeDashOffset = 0; } chart.Canvas.Children.Add(path); Shapes.Add(path); }
/// <summary> /// Draws a collection of polygons, where all polygons have the same stroke and fill. /// This performs better than calling DrawPolygon multiple times. /// </summary> /// <param name="polygons">The polygons.</param> /// <param name="fill">The fill color.</param> /// <param name="stroke">The stroke color.</param> /// <param name="thickness">The stroke thickness.</param> /// <param name="dashArray">The dash array.</param> /// <param name="lineJoin">The line join type.</param> /// <param name="aliased">if set to <c>true</c> the shape will be aliased.</param> public void DrawPolygons( IList<IList<ScreenPoint>> polygons, OxyColor fill, OxyColor stroke, double thickness, double[] dashArray, LineJoin lineJoin, bool aliased) { var path = new Path(); this.SetStroke(path, stroke, thickness, lineJoin, dashArray, aliased); if (fill.IsVisible()) { path.Fill = this.GetCachedBrush(fill); } var pg = new PathGeometry { FillRule = FillRule.Nonzero }; foreach (var polygon in polygons) { var figure = new PathFigure { IsClosed = true }; bool first = true; foreach (var p in polygon) { if (first) { figure.StartPoint = p.ToPoint(aliased); first = false; } else { figure.Segments.Add(new LineSegment { Point = p.ToPoint(aliased) }); } } pg.Figures.Add(figure); } path.Data = pg; this.Add(path); }
/// <summary> /// Actually creates the visual appearance of a node given the values provided by <see cref="RenderDataCache"/>. /// </summary> /// <remarks> /// This renders the node and the edges to the labels and adds the visuals to the <paramref name="container"/>. /// All items are arranged as if the node was located at (0,0). <see cref="CreateVisual"/> and <see cref="UpdateVisual"/> /// finally arrange the container so that the drawing is translated into the final position. /// </remarks> private void Render(IRenderContext context, INode node, VisualGroup container, RenderDataCache cache) { // store information with the visual on how we created it container.SetRenderDataCache(cache); // draw the drop shadow DrawShadow(container, cache.Size); // draw edges to node labels RenderLabelEdges(context, node, container, cache); // determine the color to use for the rendering Color color = GetNodeColor(node); // the size of node SizeD nodeSize = cache.Size; Ellipse shape = new Ellipse { Width = nodeSize.Width, Height = nodeSize.Height }; // max and min needed for reflection effect calculation double max = Math.Max(nodeSize.Width, nodeSize.Height); double min = Math.Min(nodeSize.Width, nodeSize.Height); // Create Background gradient from specified background color shape.Fill = new LinearGradientBrush() { GradientStops = { new GradientStop { Color = Color.FromArgb((byte)Math.Max(0, color.A - 50), (byte)Math.Min(255, color.R * 1.7), (byte)Math.Min(255, color.G * 1.7), (byte)Math.Min(255, color.B * 1.7)), Offset = 1 }, new GradientStop { Color = color, Offset = 0.5 }, new GradientStop { Color = Color.FromArgb((byte)Math.Max(0, color.A - 50), (byte)Math.Min(255, color.R * 1.4), (byte)Math.Min(255, color.G * 1.4), (byte)Math.Min(255, color.B * 1.4)), Offset = 0 } }, StartPoint = new Point(0, 0), EndPoint = new Point(0.5 / (nodeSize.Width / max), 1 / (nodeSize.Height / max)), SpreadMethod = GradientSpreadMethod.Pad }; // Create light reflection effects Ellipse reflection1 = new Ellipse { Width = min / 10, Height = min / 10, Fill = Brushes.White }; Ellipse reflection2 = new Ellipse { Width = min / 7, Height = min / 7, Fill = Brushes.AliceBlue }; PathGeometry reflection3 = new PathGeometry(); PathFigure figure = new PathFigure(); Point startPoint = new Point(nodeSize.Width / 2.5, nodeSize.Height / 10 * 9); Point endPoint = new Point(nodeSize.Width / 10 * 9, nodeSize.Height / 2.5); Point ctrlPoint1 = new Point(startPoint.X + (endPoint.X - startPoint.X) / 2, nodeSize.Height); Point ctrlPoint2 = new Point(nodeSize.Width, startPoint.Y + (endPoint.Y - startPoint.Y) / 2); Point ctrlPoint3 = new Point(ctrlPoint1.X, ctrlPoint1.Y - nodeSize.Height / 10); Point ctrlPoint4 = new Point(ctrlPoint2.X - nodeSize.Width / 10, ctrlPoint2.Y); figure.StartPoint = startPoint; reflection3.Figures.Add(figure); figure.Segments.Add(new BezierSegment { Point1 = ctrlPoint1, Point2 = ctrlPoint2, Point3 = endPoint }); figure.Segments.Add(new BezierSegment { Point1 = ctrlPoint4, Point2 = ctrlPoint3, Point3 = startPoint }); figure.IsFilled = true; Path p = new Path(); p.Data = reflection3; p.Fill = Brushes.AliceBlue; figure.Freeze(); // place the reflections reflection1.SetCanvasArrangeRect(new Rect(nodeSize.Width / 5, nodeSize.Height / 5, min / 10, min / 10)); reflection2.SetCanvasArrangeRect(new Rect(nodeSize.Width / 4.9, nodeSize.Height / 4.9, min / 7, min / 7)); // and add all to the container for the node container.Children.Add(shape); container.Children.Add(reflection2); container.Children.Add(reflection1); container.Children.Add(p); }
private void DrawFunnelFigure(FixedContentEditor editor) { editor.GraphicProperties.IsStroked = false; editor.GraphicProperties.FillColor = new RgbColor(231, 238, 247); editor.DrawEllipse(new Point(250, 70), 136, 48); editor.GraphicProperties.IsStroked = true; editor.GraphicProperties.StrokeColor = RgbColors.White; editor.GraphicProperties.StrokeThickness = 1; editor.GraphicProperties.FillColor = new RgbColor(91, 155, 223); editor.DrawEllipse(new Point(289, 77), 48, 48); editor.TextProperties.Font = FontsRepository.Helvetica; editor.TextProperties.HorizontalAlignment = HorizontalTextAlignment.Center; editor.TextProperties.VerticalAlignment = VerticalTextAlignment.Center; editor.TextProperties.TextBlockWidth = 96; editor.TextProperties.TextBlockHeight = 96; using (editor.SaveGraphicProperties()) { editor.Position.Translate(291, 229); editor.GraphicProperties.FillColor = RgbColors.White; editor.DrawText("Fonts"); } editor.Position.Translate(0, 0); editor.DrawEllipse(new Point(238, 299), 48, 48); using (editor.SaveGraphicProperties()) { editor.Position.Translate(190, 251); editor.GraphicProperties.FillColor = RgbColors.White; editor.DrawText("Images"); } editor.Position.Translate(0, 0); editor.DrawEllipse(new Point(307, 372), 48, 48); using (editor.SaveGraphicProperties()) { editor.Position.Translate(259, 324); editor.GraphicProperties.FillColor = RgbColors.White; editor.DrawText("Shapes"); } editor.Position.Translate(0, 0); PathGeometry arrow = new PathGeometry(); PathFigure figure = arrow.Figures.AddPathFigure(); figure.StartPoint = new Point(287, 447); figure.IsClosed = true; figure.Segments.AddLineSegment(new Point(287, 463)); figure.Segments.AddLineSegment(new Point(278, 463)); figure.Segments.AddLineSegment(new Point(300, 479)); figure.Segments.AddLineSegment(new Point(322, 463)); figure.Segments.AddLineSegment(new Point(313, 463)); figure.Segments.AddLineSegment(new Point(313, 447)); editor.DrawPath(arrow); editor.GraphicProperties.FillColor = new RgbColor(80, 255, 255, 255); editor.GraphicProperties.IsStroked = true; editor.GraphicProperties.StrokeThickness = 1; editor.GraphicProperties.StrokeColor = new RgbColor(91, 155, 223); PathGeometry funnel = new PathGeometry(); funnel.FillRule = FillRule.EvenOdd; figure = funnel.Figures.AddPathFigure(); figure.IsClosed = true; figure.StartPoint = new Point(164, 270); figure.Segments.AddArcSegment(new Point(436, 270), 136, 48); figure.Segments.AddArcSegment(new Point(164, 270), 136, 48); figure = funnel.Figures.AddPathFigure(); figure.IsClosed = true; figure.StartPoint = new Point(151, 270); figure.Segments.AddArcSegment(new Point(449, 270), 149, 61); figure.Segments.AddLineSegment(new Point(332, 440)); figure.Segments.AddArcSegment(new Point(268, 440), 16, 4); editor.DrawPath(funnel); using (editor.SaveGraphicProperties()) { using (editor.SaveTextProperties()) { editor.Position.Translate(164, 484); editor.GraphicProperties.FillColor = RgbColors.Black; editor.TextProperties.HorizontalAlignment = HorizontalTextAlignment.Center; editor.TextProperties.VerticalAlignment = VerticalTextAlignment.Top; editor.TextProperties.TextBlockWidth = 272; editor.TextProperties.FontSize = 18; editor.DrawText("PDF"); } } }
/// <summary> /// Render callback. /// </summary> protected override void OnRender(DrawingContext drawingContext) { CornerRadius cornerRadius = CornerRadius; Rect shadowBounds = new Rect(new Point(ShadowDepth, ShadowDepth), new Size(RenderSize.Width, RenderSize.Height)); Color color = Color; if (shadowBounds.Width > 0 && shadowBounds.Height > 0 && color.A > 0) { // The shadow is drawn with a dark center the size of the shadow bounds // deflated by shadow depth on each side. double centerWidth = shadowBounds.Right - shadowBounds.Left - 2 * ShadowDepth; double centerHeight = shadowBounds.Bottom - shadowBounds.Top - 2 * ShadowDepth; // Clamp corner radii to be less than 1/2 the side of the inner shadow bounds double maxRadius = Math.Min(centerWidth * 0.5, centerHeight * 0.5); cornerRadius.TopLeft = Math.Min(cornerRadius.TopLeft, maxRadius); cornerRadius.TopRight = Math.Min(cornerRadius.TopRight, maxRadius); cornerRadius.BottomLeft = Math.Min(cornerRadius.BottomLeft, maxRadius); cornerRadius.BottomRight = Math.Min(cornerRadius.BottomRight, maxRadius); // Get the brushes for the 9 regions Brush[] brushes = GetBrushes(color, cornerRadius); // Snap grid to device pixels double centerTop = shadowBounds.Top + ShadowDepth; double centerLeft = shadowBounds.Left + ShadowDepth; double centerRight = shadowBounds.Right - ShadowDepth; double centerBottom = shadowBounds.Bottom - ShadowDepth; // Because of different corner radii there are 6 potential x (or y) lines to snap to double[] guidelineSetX = new double[] { centerLeft, centerLeft + cornerRadius.TopLeft, centerRight - cornerRadius.TopRight, centerLeft + cornerRadius.BottomLeft, centerRight - cornerRadius.BottomRight, centerRight }; double[] guidelineSetY = new double[] { centerTop, centerTop + cornerRadius.TopLeft, centerTop + cornerRadius.TopRight, centerBottom - cornerRadius.BottomLeft, centerBottom - cornerRadius.BottomRight, centerBottom }; drawingContext.PushGuidelineSet(new GuidelineSet(guidelineSetX, guidelineSetY)); // The corner rectangles are drawn drawn ShadowDepth pixels bigger to // account for the blur cornerRadius.TopLeft = cornerRadius.TopLeft + ShadowDepth; cornerRadius.TopRight = cornerRadius.TopRight + ShadowDepth; cornerRadius.BottomLeft = cornerRadius.BottomLeft + ShadowDepth; cornerRadius.BottomRight = cornerRadius.BottomRight + ShadowDepth; // Draw Top row Rect topLeft = new Rect(shadowBounds.Left, shadowBounds.Top, cornerRadius.TopLeft, cornerRadius.TopLeft); drawingContext.DrawRectangle(brushes[TopLeft], null, topLeft); double topWidth = guidelineSetX[2] - guidelineSetX[1]; if (topWidth > 0) { Rect top = new Rect(guidelineSetX[1], shadowBounds.Top, topWidth, ShadowDepth); drawingContext.DrawRectangle(brushes[Top], null, top); } Rect topRight = new Rect(guidelineSetX[2], shadowBounds.Top, cornerRadius.TopRight, cornerRadius.TopRight); drawingContext.DrawRectangle(brushes[TopRight], null, topRight); // Middle row double leftHeight = guidelineSetY[3] - guidelineSetY[1]; if (leftHeight > 0) { Rect left = new Rect(shadowBounds.Left, guidelineSetY[1], ShadowDepth, leftHeight); drawingContext.DrawRectangle(brushes[Left], null, left); } double rightHeight = guidelineSetY[4] - guidelineSetY[2]; if (rightHeight > 0) { Rect right = new Rect(guidelineSetX[5], guidelineSetY[2], ShadowDepth, rightHeight); drawingContext.DrawRectangle(brushes[Right], null, right); } // Bottom row Rect bottomLeft = new Rect(shadowBounds.Left, guidelineSetY[3], cornerRadius.BottomLeft, cornerRadius.BottomLeft); drawingContext.DrawRectangle(brushes[BottomLeft], null, bottomLeft); double bottomWidth = guidelineSetX[4] - guidelineSetX[3]; if (bottomWidth > 0) { Rect bottom = new Rect(guidelineSetX[3], guidelineSetY[5], bottomWidth, ShadowDepth); drawingContext.DrawRectangle(brushes[Bottom], null, bottom); } Rect bottomRight = new Rect(guidelineSetX[4], guidelineSetY[4], cornerRadius.BottomRight, cornerRadius.BottomRight); drawingContext.DrawRectangle(brushes[BottomRight], null, bottomRight); // Fill Center // Because the heights of the top/bottom rects and widths of the left/right rects are fixed // and the corner rects are drawn with the size of the corner, the center // may not be a square. In this case, create a path to fill the area // When the target object's corner radius is 0, only need to draw one rect if (cornerRadius.TopLeft == ShadowDepth && cornerRadius.TopLeft == cornerRadius.TopRight && cornerRadius.TopLeft == cornerRadius.BottomLeft && cornerRadius.TopLeft == cornerRadius.BottomRight) { // All corners of target are 0, render one large rectangle Rect center = new Rect(guidelineSetX[0], guidelineSetY[0], centerWidth, centerHeight); drawingContext.DrawRectangle(brushes[Center], null, center); } else { // If the corner radius is TL=2, TR=1, BL=0, BR=2 the following shows the shape that needs to be created. // _________________ // | |_ // _ _| | // | | // | _ _| // | | // |___________________| // The missing corners of the shape are filled with the radial gradients drawn above // Define shape counter clockwise PathFigure figure = new PathFigure(); if (cornerRadius.TopLeft > ShadowDepth) { figure.StartPoint = new Point(guidelineSetX[1], guidelineSetY[0]); figure.Segments.Add(new LineSegment(new Point(guidelineSetX[1], guidelineSetY[1]), true)); figure.Segments.Add(new LineSegment(new Point(guidelineSetX[0], guidelineSetY[1]), true)); } else { figure.StartPoint = new Point(guidelineSetX[0], guidelineSetY[0]); } if (cornerRadius.BottomLeft > ShadowDepth) { figure.Segments.Add(new LineSegment(new Point(guidelineSetX[0], guidelineSetY[3]), true)); figure.Segments.Add(new LineSegment(new Point(guidelineSetX[3], guidelineSetY[3]), true)); figure.Segments.Add(new LineSegment(new Point(guidelineSetX[3], guidelineSetY[5]), true)); } else { figure.Segments.Add(new LineSegment(new Point(guidelineSetX[0], guidelineSetY[5]), true)); } if (cornerRadius.BottomRight > ShadowDepth) { figure.Segments.Add(new LineSegment(new Point(guidelineSetX[4], guidelineSetY[5]), true)); figure.Segments.Add(new LineSegment(new Point(guidelineSetX[4], guidelineSetY[4]), true)); figure.Segments.Add(new LineSegment(new Point(guidelineSetX[5], guidelineSetY[4]), true)); } else { figure.Segments.Add(new LineSegment(new Point(guidelineSetX[5], guidelineSetY[5]), true)); } if (cornerRadius.TopRight > ShadowDepth) { figure.Segments.Add(new LineSegment(new Point(guidelineSetX[5], guidelineSetY[2]), true)); figure.Segments.Add(new LineSegment(new Point(guidelineSetX[2], guidelineSetY[2]), true)); figure.Segments.Add(new LineSegment(new Point(guidelineSetX[2], guidelineSetY[0]), true)); } else { figure.Segments.Add(new LineSegment(new Point(guidelineSetX[5], guidelineSetY[0]), true)); } figure.IsClosed = true; figure.Freeze(); PathGeometry geometry = new PathGeometry(); geometry.Figures.Add(figure); geometry.Freeze(); drawingContext.DrawGeometry(brushes[Center], null, geometry); } drawingContext.Pop(); } }
public override void Plot(bool animate = true) { _isPrimitive = Values.Count >= 1 && Values[0].GetType().IsPrimitive; var rr = PointRadius < 5 ? 5 : PointRadius; var f = (Chart.Invert ? CurrentXAxis : CurrentYAxis).GetFormatter(); var s = 0; var so = 0; var isUp = Chart is IUnitaryPoints; foreach (var segment in Values.Points.AsSegments().Where(segment => segment.Count != 0)) { LineAndAreaShape area; bool isNew = false; var ofPt = new Point(); if (_areas.Count <= s) { var path = new Path(); BindingOperations.SetBinding(path, Shape.StrokeProperty, new Binding { Path = new PropertyPath("Stroke"), Source = this }); BindingOperations.SetBinding(path, Shape.FillProperty, new Binding { Path = new PropertyPath("Fill"), Source = this }); BindingOperations.SetBinding(path, Shape.StrokeThicknessProperty, new Binding { Path = new PropertyPath("StrokeThickness"), Source = this }); BindingOperations.SetBinding(path, VisibilityProperty, new Binding { Path = new PropertyPath("Visibility"), Source = this }); BindingOperations.SetBinding(path, Panel.ZIndexProperty, new Binding { Path = new PropertyPath(Panel.ZIndexProperty), Source = this }); BindingOperations.SetBinding(path, Shape.StrokeDashArrayProperty, new Binding { Path = new PropertyPath(StrokeDashArrayProperty), Source = this }); var geometry = new PathGeometry(); area = new LineAndAreaShape(new PathFigure(), path); geometry.Figures.Add(area.Figure); path.Data = geometry; _areas.Add(area); Chart.DrawMargin.Children.Add(path); isNew = true; if (isUp) { if (Chart.Invert) { ofPt = new Point(0, Methods.GetUnitWidth(AxisTags.Y, Chart, ScalesYAt) * .5); Canvas.SetTop(path, ofPt.Y); } else { ofPt = new Point(Methods.GetUnitWidth(AxisTags.X, Chart, ScalesYAt) * .5, 0); Canvas.SetLeft(path, ofPt.X); } } } else { area = _areas[s]; if (isUp) { if (Chart.Invert) { ofPt = new Point(0, Methods.GetUnitWidth(AxisTags.Y, Chart, ScalesYAt) * .5); Canvas.SetTop(area.Path, ofPt.Y); } else { ofPt = new Point(Methods.GetUnitWidth(AxisTags.X, Chart, ScalesYAt) * .5, 0); Canvas.SetLeft(area.Path, ofPt.X); } } } var p0 = ToDrawMargin(segment[0], ScalesXAt, ScalesYAt).AsPoint(); area.Figure.StartPoint = isNew ? (Chart.Invert ? new Point(ToPlotArea(CurrentXAxis.MinLimit, AxisTags.X, ScalesXAt), p0.X) : new Point(p0.X, ToPlotArea(CurrentYAxis.MinLimit, AxisTags.Y, ScalesYAt))) : p0; area.Figure.BeginAnimation(PathFigure.StartPointProperty, new PointAnimation(area.Figure.StartPoint, segment.Count > 0 ? p0 : new Point(), AnimSpeed)); AnimatableSegments previous = null; var isVirgin = true; var first = new Point(); var last = new Point(); for (var i = 0; i < segment.Count; i++) { var point = segment[i]; point.ChartLocation = ToDrawMargin(point, ScalesXAt, ScalesYAt).AsPoint(); if (isUp) { point.ChartLocation = new Point(point.ChartLocation.X + ofPt.X, point.ChartLocation.Y + ofPt.Y); } if (isVirgin) { isVirgin = false; first = point.ChartLocation; } var visual = GetVisual(segment[i]); PlaceVisual(visual, point.ChartLocation, rr); if (DataLabels) { Label(point, f, point.ChartLocation); } if (visual.IsNew) { AddToCanvas(visual, point); } var helper = GetSegmentHelper(point.Key, segment[i].Instance, area.Figure); helper.Data = i == segment.Count - 1 ? new BezierData(previous != null ? previous.Data.P3 : area.Figure.StartPoint) //last line is a dummy line, just to keep algorithm simple. : CalculateBezier(i, segment); helper.Previous = previous != null && previous.IsNew ? previous.Previous : previous; helper.Animate(i + so, Chart, so); previous = helper; last = point.ChartLocation; } if (area != null) { area.DrawLimits(first, last, new Point(ToDrawMargin(CurrentXAxis.MinLimit, AxisTags.X, ScalesXAt), ToDrawMargin(CurrentYAxis.MinLimit, AxisTags.Y, ScalesYAt)), Chart.Invert); } #if DEBUG Trace.WriteLine("Segments count: " + area.Figure.Segments.Count); #endif s++; so += segment.Count; } }
public MatrixAnimationUsingPathDoesRotateWithTangentExample() { this.Margin = new Thickness(20); // Create a NameScope for the page so that // we can use Storyboards. NameScope.SetNameScope(this, new NameScope()); // Create a button. Button aButton = new Button(); aButton.MinWidth = 100; aButton.Content = "A Button"; // Create a MatrixTransform. This transform // will be used to move the button. MatrixTransform buttonMatrixTransform = new MatrixTransform(); aButton.RenderTransform = buttonMatrixTransform; // Register the transform's name with the page // so that it can be targeted by a Storyboard. this.RegisterName("ButtonMatrixTransform", buttonMatrixTransform); // Create a Canvas to contain the button // and add it to the page. // Although this example uses a Canvas, // any type of panel will work. Canvas mainPanel = new Canvas(); mainPanel.Width = 400; mainPanel.Height = 400; mainPanel.Children.Add(aButton); this.Content = mainPanel; // Create the animation path. PathGeometry animationPath = new PathGeometry(); PathFigure pFigure = new PathFigure(); pFigure.StartPoint = new Point(10, 100); PolyBezierSegment pBezierSegment = new PolyBezierSegment(); pBezierSegment.Points.Add(new Point(35, 0)); pBezierSegment.Points.Add(new Point(135, 0)); pBezierSegment.Points.Add(new Point(160, 100)); pBezierSegment.Points.Add(new Point(180, 190)); pBezierSegment.Points.Add(new Point(285, 200)); pBezierSegment.Points.Add(new Point(310, 100)); pFigure.Segments.Add(pBezierSegment); animationPath.Figures.Add(pFigure); // Freeze the PathGeometry for performance benefits. animationPath.Freeze(); // Create a MatrixAnimationUsingPath to move the // button along the path by animating // its MatrixTransform. MatrixAnimationUsingPath matrixAnimation = new MatrixAnimationUsingPath(); matrixAnimation.PathGeometry = animationPath; matrixAnimation.Duration = TimeSpan.FromSeconds(5); matrixAnimation.RepeatBehavior = RepeatBehavior.Forever; // Set the animation's DoesRotateWithTangent property // to true so that rotates the rectangle in addition // to moving it. matrixAnimation.DoesRotateWithTangent = true; // Set the animation to target the Matrix property // of the MatrixTransform named "ButtonMatrixTransform". Storyboard.SetTargetName(matrixAnimation, "ButtonMatrixTransform"); Storyboard.SetTargetProperty(matrixAnimation, new PropertyPath(MatrixTransform.MatrixProperty)); // Create a Storyboard to contain and apply the animation. Storyboard pathAnimationStoryboard = new Storyboard(); pathAnimationStoryboard.Children.Add(matrixAnimation); // Start the storyboard when the button is loaded. aButton.Loaded += delegate(object sender, RoutedEventArgs e) { // Start the storyboard. pathAnimationStoryboard.Begin(this); }; }
public static TextFrame ReadXml(XmlReader reader) { TextFrame tf = new TextFrame(); if (reader.HasAttributes) { tf.Self = System.Convert.ToString(reader.GetAttribute("Self")); tf.ParentStory = System.Convert.ToString(reader.GetAttribute("ParentStory")); tf.PreviousTextFrame = System.Convert.ToString(reader.GetAttribute("PreviousTextFrame")); tf.NextTextFrame = System.Convert.ToString(reader.GetAttribute("NextTextFrame")); tf.ContentType = (ContentType)Enum.Parse(typeof(ContentType), reader.GetAttribute("ContentType")); tf.StrokeWeight = Parser.ParseDouble(reader.GetAttribute("StrokeWeight")); tf.GradientFillStart = new UnitPointType(reader.GetAttribute("GradientFillStart")); tf.GradientFillLength = Parser.ParseDouble(reader.GetAttribute("GradientFillLength")); tf.GradientFillAngle = Parser.ParseDouble(reader.GetAttribute("GradientFillAngle")); tf.GradientStrokeStart = new UnitPointType(reader.GetAttribute("GradientStrokeStart")); tf.GradientStrokeLength = Parser.ParseDouble(reader.GetAttribute("GradientStrokeLength")); tf.GradientStrokeAngle = Parser.ParseDouble(reader.GetAttribute("GradientStrokeAngle")); tf.ItemLayer = System.Convert.ToString(reader.GetAttribute("ItemLayer")); tf.Locked = Parser.ParseBoolean(reader.GetAttribute("Locked")); tf.LocalDisplaySetting = (DisplaySettingOptions?)Parser.ParseEnum <DisplaySettingOptions>(reader.GetAttribute("LocalDisplaySetting")); tf.GradientFillHiliteLength = Parser.ParseDouble(reader.GetAttribute("GradientFillHiliteLength")); tf.GradientFillHiliteAngle = Parser.ParseDouble(reader.GetAttribute("GradientFillHiliteAngle")); tf.GradientStrokeHiliteLength = Parser.ParseDouble(reader.GetAttribute("GradientStrokeHiliteLength")); tf.GradientStrokeHiliteAngle = Parser.ParseDouble(reader.GetAttribute("GradientStrokeHiliteAngle")); tf.AppliedObjectStyle = System.Convert.ToString(reader.GetAttribute("AppliedObjectStyle")); tf.Visible = Parser.ParseBoolean(reader.GetAttribute("Visible")); tf.Name = System.Convert.ToString(reader.GetAttribute("Name")); tf.ItemTransform = System.Convert.ToString(reader.GetAttribute("ItemTransform")); } if (reader.IsEmptyElement) { return(tf); } while (reader.Read()) { if ((string)reader.Name == "Properties") { while (reader.Read()) { if ((string)reader.Name == "PathGeometry") { tf.PathGeometry = PathGeometry.ReadXml(reader); } else if ((string)reader.Name == "Properties") { if (reader.NodeType == XmlNodeType.EndElement) { break; } } else { if (reader.NodeType == XmlNodeType.Element) { Debug.WriteLine("Unrecognized element: {0} in element: {1}", reader.Name, "TextFrame - Properties"); } } } } else if ((string)reader.Name == "TextFramePreference") { tf.TextFramePreference = TextFramePreference.ReadXml(reader); } else if ((string)reader.Name == "TextWrapPreference") { tf.TextWrapPreference = TextWrapPreference.ReadXml(reader); } else if ((string)reader.Name == "TextFrame") { if (reader.NodeType == XmlNodeType.EndElement) { break; } } else { if (reader.NodeType == XmlNodeType.Element) { Debug.WriteLine("Unrecognized element: {0} in element: {1}", reader.Name, "TextFrame"); } } } return(tf); }
public static PathData ToCGPath(this Geometry geometry, Transform renderTransform = null) { PathData pathData = new PathData { Data = new CGPath() }; CGAffineTransform transform; if (renderTransform == null) { transform = CGAffineTransform.MakeIdentity(); } else { transform = renderTransform.ToCGAffineTransform(); } if (geometry is LineGeometry) { LineGeometry lineGeometry = geometry as LineGeometry; pathData.Data.MoveToPoint(transform, lineGeometry.StartPoint.ToPointF()); pathData.Data.AddLineToPoint(transform, lineGeometry.EndPoint.ToPointF()); } else if (geometry is RectangleGeometry) { Rect rect = (geometry as RectangleGeometry).Rect; pathData.Data.AddRect(transform, new CGRect(rect.X, rect.Y, rect.Width, rect.Height)); } else if (geometry is EllipseGeometry) { EllipseGeometry ellipseGeometry = geometry as EllipseGeometry; CGRect rect = new CGRect( ellipseGeometry.Center.X - ellipseGeometry.RadiusX, ellipseGeometry.Center.Y - ellipseGeometry.RadiusY, ellipseGeometry.RadiusX * 2, ellipseGeometry.RadiusY * 2); pathData.Data.AddEllipseInRect(transform, rect); } else if (geometry is GeometryGroup) { GeometryGroup geometryGroup = geometry as GeometryGroup; pathData.IsNonzeroFillRule = geometryGroup.FillRule == FillRule.Nonzero; foreach (Geometry child in geometryGroup.Children) { PathData pathChild = child.ToCGPath(renderTransform); pathData.Data.AddPath(pathChild.Data); } } else if (geometry is PathGeometry) { PathGeometry pathGeometry = geometry as PathGeometry; pathData.IsNonzeroFillRule = pathGeometry.FillRule == FillRule.Nonzero; foreach (PathFigure pathFigure in pathGeometry.Figures) { pathData.Data.MoveToPoint(transform, pathFigure.StartPoint.ToPointF()); Point lastPoint = pathFigure.StartPoint; foreach (PathSegment pathSegment in pathFigure.Segments) { // LineSegment if (pathSegment is LineSegment) { LineSegment lineSegment = pathSegment as LineSegment; pathData.Data.AddLineToPoint(transform, lineSegment.Point.ToPointF()); lastPoint = lineSegment.Point; } // PolyLineSegment else if (pathSegment is PolyLineSegment) { PolyLineSegment polylineSegment = pathSegment as PolyLineSegment; PointCollection points = polylineSegment.Points; for (int i = 0; i < points.Count; i++) { pathData.Data.AddLineToPoint(transform, points[i].ToPointF()); } lastPoint = points[points.Count - 1]; } // BezierSegment if (pathSegment is BezierSegment) { BezierSegment bezierSegment = pathSegment as BezierSegment; pathData.Data.AddCurveToPoint( transform, bezierSegment.Point1.ToPointF(), bezierSegment.Point2.ToPointF(), bezierSegment.Point3.ToPointF()); lastPoint = bezierSegment.Point3; } // PolyBezierSegment else if (pathSegment is PolyBezierSegment) { PolyBezierSegment polyBezierSegment = pathSegment as PolyBezierSegment; PointCollection points = polyBezierSegment.Points; if (points.Count >= 3) { for (int i = 0; i < points.Count; i += 3) { pathData.Data.AddCurveToPoint( transform, points[i].ToPointF(), points[i + 1].ToPointF(), points[i + 2].ToPointF()); } } lastPoint = points[points.Count - 1]; } // QuadraticBezierSegment if (pathSegment is QuadraticBezierSegment) { QuadraticBezierSegment bezierSegment = pathSegment as QuadraticBezierSegment; pathData.Data.AddQuadCurveToPoint( transform, new nfloat(bezierSegment.Point1.X), new nfloat(bezierSegment.Point1.Y), new nfloat(bezierSegment.Point2.X), new nfloat(bezierSegment.Point2.Y)); lastPoint = bezierSegment.Point2; } // PolyQuadraticBezierSegment else if (pathSegment is PolyQuadraticBezierSegment) { PolyQuadraticBezierSegment polyBezierSegment = pathSegment as PolyQuadraticBezierSegment; PointCollection points = polyBezierSegment.Points; if (points.Count >= 2) { for (int i = 0; i < points.Count; i += 2) { pathData.Data.AddQuadCurveToPoint( transform, new nfloat(points[i + 0].X), new nfloat(points[i + 0].Y), new nfloat(points[i + 1].X), new nfloat(points[i + 1].Y)); } } lastPoint = points[points.Count - 1]; } // ArcSegment else if (pathSegment is ArcSegment) { ArcSegment arcSegment = pathSegment as ArcSegment; List <Point> points = new List <Point>(); GeometryHelper.FlattenArc( points, lastPoint, arcSegment.Point, arcSegment.Size.Width, arcSegment.Size.Height, arcSegment.RotationAngle, arcSegment.IsLargeArc, arcSegment.SweepDirection == SweepDirection.CounterClockwise, 1); CGPoint[] cgpoints = new CGPoint[points.Count]; for (int i = 0; i < points.Count; i++) { cgpoints[i] = transform.TransformPoint(points[i].ToPointF()); } pathData.Data.AddLines(cgpoints); lastPoint = points.Count > 0 ? points[points.Count - 1] : Point.Zero; } } if (pathFigure.IsClosed) { pathData.Data.CloseSubpath(); } } } return(pathData); }
private void RenderColorChart(DrawingContext dc, double width, double height) { //Determine the radius of the overall circle; we want this to be square in order to get a true circle, so use the min. extent double dblRadius = Math.Min(width / 2, height / 2); var szRadius = new Size(dblRadius, dblRadius); //Calculate the center of the control var ptCenter = new Point(dblRadius, dblRadius); if (SectorBrushes != null && SectorBrushes.Count > 1) { //The radius (degrees) that a single sector will cover double dblSectorRadius = 360d / SectorBrushes.Count; for (int intSectorCounter = 0; intSectorCounter < SectorBrushes.Count; intSectorCounter++) { //Get the start- and end-points of the current arc segment to be drawn var ptArcStartPoint = GetPointAtAngle(ptCenter, dblRadius, intSectorCounter * dblSectorRadius); var ptArcEndPoint = GetPointAtAngle(ptCenter, dblRadius, (intSectorCounter + 1) * dblSectorRadius); //The bounding rectangle of the current arc Sector var rctArcRect = new Rect(ptArcStartPoint, ptArcEndPoint); //Construct the shape var pg = new PathGeometry(); var pf = new PathFigure(); pg.Figures.Add(pf); pf.StartPoint = ptArcStartPoint; pf.IsFilled = true; // Add the current sector's arc-segment pf.Segments.Add( new ArcSegment( ptArcEndPoint, szRadius, dblSectorRadius, (dblSectorRadius >= 180), SweepDirection.Clockwise, false ) ); // Add a line that ends in the center of the control pf.Segments.Add( new LineSegment(ptCenter, true) ); // Close the figure (IOW, this will add a line between the center of the control and // the arc's start point, resulting in a pie shape) pf.IsClosed = true; //Draw the arc (skipping the Pen used for drawing a line around the shape) dc.DrawGeometry(SectorBrushes[intSectorCounter], null, pg); } } else if (SectorBrushes != null && SectorBrushes.Count == 1) { dc.DrawEllipse(SectorBrushes[0], null, ptCenter, dblRadius, dblRadius); } //Draw a circle around the sectors, if both a non-transparent color and a StrokeWidth>0 have been supplied. if (StrokeColor != null && StrokeColor != Colors.Transparent && StrokeWidth > 0) { dc.DrawEllipse(null, CachedStrokePen, ptCenter, dblRadius, dblRadius); } }
public PathGeometry ObtenerCamino(Posicion posicionInicial, Posicion posicionFinal) { // El sentido horizontal del desplazamiento depende de la localizacion horizontal // de ambas posiciones int direccion = (posicionInicial.PosicionX < posicionFinal.PosicionX) ? 1 : -1; PathGeometry camino = new PathGeometry(); PathFigure caminoFigura = new PathFigure(); caminoFigura.StartPoint = new Point(posicionInicial.PosicionX, posicionInicial.PosicionY); PolyBezierSegment segmentoBezier = new PolyBezierSegment(); caminoFigura.Segments.Add(segmentoBezier); camino.Figures.Add(caminoFigura); int anchoCiclo; int cantCiclos = 3; int puntoNeutroY = 160; int posicionMaximaY = puntoNeutroY + 64; int posicionMinimaY = puntoNeutroY - 64; int posicionXActual = posicionInicial.PosicionX; int posicionYActual = posicionInicial.PosicionY; Random numero = new Random(); for (int i = 1; i <= cantCiclos; i++) { // Si es el ultimo ciclo completo el ancho que falta para llenar hasta el punto máximo de X if (i == cantCiclos) { if (direccion == 1) { anchoCiclo = Convert.ToInt32(posicionFinal.PosicionX) - posicionXActual; } else { anchoCiclo = posicionXActual; } } else { // No es el ultimo ciclo el ancho del mismo es al azar anchoCiclo = numero.Next(200, 330); } // PosicionXActual es la posicon del ultimo ciclo procesado la posicion actual es la siguiente: int posicionXTemporal = posicionXActual; // Generar puntos intermedios while (posicionXTemporal != posicionXActual + (anchoCiclo * direccion)) { if (direccion == 1) { posicionXTemporal = numero.Next(posicionXTemporal + 60, posicionXTemporal + 120); } else { posicionXTemporal = numero.Next(posicionXTemporal - 120, posicionXTemporal - 60); } posicionYActual = numero.Next(posicionYActual - 80, posicionYActual + 80); if (((posicionXTemporal > posicionXActual + anchoCiclo) && (direccion == 1)) || ((posicionXTemporal < posicionXActual - anchoCiclo) && (direccion == -1))) { posicionXTemporal = posicionXActual + anchoCiclo * direccion; } if (posicionYActual > posicionMaximaY) { posicionYActual = posicionMaximaY; } if (posicionYActual < posicionMinimaY) { posicionYActual = posicionMinimaY; } segmentoBezier.Points.Add(new Point(posicionXTemporal, posicionYActual)); } } return(camino); }
///<summary>生成图元Brush</summary> protected void genSymbolBrush() { SolidColorBrush defaultbrush = new SolidColorBrush(Colors.Lime); Brush brush; foreach (IGrouping <string, DataRow> g in dtsymbol.AsEnumerable().GroupBy(p => p.Field <string>("svgsymbolid"))) { string sid = g.Key; string name = g.First().Field <string>("name"); DrawingGroup drawgroup = new DrawingGroup(); GeometryDrawing aDrawing; double sizeX = 10; double sizeY = 10; int idx = 0; foreach (DataRow item in dtsymbol.AsEnumerable().Where(p => p.Field <string>("svgsymbolid") == sid)) { if (idx == 0)//获取尺寸 { Rect tmp = Rect.Parse(item["viewbox"].ToString()); sizeX = tmp.Width; sizeY = tmp.Height; } string shapetype = item["shapetype"].ToString(); string data = item["data"].ToString(); if (shapetype == "circle") { Regex regex = new Regex("(\\d*.?\\d*,\\d*.?\\d*)\\|(\\d*.?\\d*)", RegexOptions.Multiline); Match m = regex.Match(data); if (m.Success) { Point pc = Point.Parse(m.Groups[1].Value); double r = double.Parse(m.Groups[2].Value); EllipseGeometry geo = new EllipseGeometry(pc, r, r); aDrawing = new GeometryDrawing(); aDrawing.Geometry = geo; Pen pen = new Pen(); double thickness = double.Parse(item["width"].ToString()); thickness = thickness < 2 ? 2 : thickness; pen.Thickness = thickness; brush = defaultbrush;//强制缺省用黄色//brush = anaBrush(item["fill"].ToString()); pen.Brush = brush; aDrawing.Pen = pen; drawgroup.Children.Add(aDrawing); } } else if (shapetype == "path") { Geometry geo = PathGeometry.Parse(data); aDrawing = new GeometryDrawing(); aDrawing.Geometry = geo; brush = defaultbrush;//强制缺省用黄色//brush = anaBrush(item["fill"].ToString()); aDrawing.Brush = brush; Pen pen = new Pen(); pen.Thickness = double.Parse(item["width"].ToString()); brush = defaultbrush; pen.Brush = brush; aDrawing.Pen = pen; drawgroup.Children.Add(aDrawing); } idx++; } DrawingBrush myDrawingBrush = new DrawingBrush(); myDrawingBrush.Drawing = drawgroup; pSymbol sym = new pSymbol() { id = sid, sizeX = sizeX, sizeY = sizeY, brush = myDrawingBrush, name = name }; //可选以文件生成材质, 否则以brush生成材质 //if (sid == "SubstationEntityDisH") // sym.texturefile = "SubstationEntityDisH.dds"; //if (sid == "SwitchStationOpen") // sym.texturefile = "SwitchStationOpen.dds"; //if (sid == "Pole") // sym.texturefile = "Pole.dds"; uc.objManager.zSymbols.Add(sid, sym); } }
public override void OnSeriesUpdateStart() { ActiveSplitters = 0; if (SplittersCollector == int.MaxValue - 1) { //just in case! Splitters.ForEach(s => s.SplitterCollectorIndex = 0); SplittersCollector = 0; } SplittersCollector++; if (Figure != null && Values != null) { var yIni = ChartFunctions.ToDrawMargin(Values.Limit2.Min, AxisOrientation.Y, Model.Chart, ScalesYAt); if (Model.Chart.View.DisableAnimations) { Figure.StartPoint = new Point(0, yIni); } else { Figure.BeginAnimation(PathFigure.StartPointProperty, new PointAnimation(new Point(0, yIni), Model.Chart.View.AnimationsSpeed)); } } if (IsPathInitialized) { return; } IsPathInitialized = true; Path = new Path(); BindingOperations.SetBinding(Path, Shape.StrokeProperty, new Binding { Path = new PropertyPath("Stroke"), Source = this }); BindingOperations.SetBinding(Path, Shape.FillProperty, new Binding { Path = new PropertyPath("Fill"), Source = this }); BindingOperations.SetBinding(Path, Shape.StrokeThicknessProperty, new Binding { Path = new PropertyPath("StrokeThickness"), Source = this }); BindingOperations.SetBinding(Path, VisibilityProperty, new Binding { Path = new PropertyPath("Visibility"), Source = this }); BindingOperations.SetBinding(Path, Panel.ZIndexProperty, new Binding { Path = new PropertyPath(Panel.ZIndexProperty), Source = this }); BindingOperations.SetBinding(Path, Shape.StrokeDashArrayProperty, new Binding { Path = new PropertyPath(StrokeDashArrayProperty), Source = this }); var geometry = new PathGeometry(); Figure = new PathFigure(); geometry.Figures.Add(Figure); Path.Data = geometry; Model.Chart.View.AddToDrawMargin(Path); var y = ChartFunctions.ToDrawMargin(ActualValues.Limit2.Min, AxisOrientation.Y, Model.Chart, ScalesYAt); Figure.StartPoint = new Point(0, y); var i = Model.Chart.View.Series.IndexOf(this); Panel.SetZIndex(Path, Model.Chart.View.Series.Count - i); }
private void CreateGeometries(Direct2DFactory factory) { Ellipse circle1 = new Ellipse(75, 75, 50, 50); this._circleGeometry1 = factory.CreateEllipseGeometry(circle1); Ellipse circle2 = new Ellipse(125, 75, 50, 50); this._circleGeometry2 = factory.CreateEllipseGeometry(circle2); // Union this._geometryUnion = factory.CreatePathGeometry(); using (GeometrySink sink = this._geometryUnion.Open()) { this._circleGeometry1.CombineWithGeometry(this._circleGeometry2, CombineMode.Union, Matrix3x2.Identity, 0.25f, sink); sink.Close(); } // Intersect this._geometryIntersect = factory.CreatePathGeometry(); using (GeometrySink sink = this._geometryIntersect.Open()) { this._circleGeometry1.CombineWithGeometry(this._circleGeometry2, CombineMode.Intersect, Matrix3x2.Identity, 0.25f, sink); sink.Close(); } // Xor this._geometryXor = factory.CreatePathGeometry(); using (GeometrySink sink = this._geometryXor.Open()) { this._circleGeometry1.CombineWithGeometry(this._circleGeometry2, CombineMode.Xor, Matrix3x2.Identity, 0.25f, sink); sink.Close(); } // Exclude this._geometryExclude = factory.CreatePathGeometry(); using (GeometrySink sink = this._geometryExclude.Open()) { this._circleGeometry1.CombineWithGeometry(this._circleGeometry2, CombineMode.Exclude, Matrix3x2.Identity, 0.25f, sink); sink.Close(); } }
/// <summary> /// Draws a collection of polygons, where all polygons have the same stroke and fill. /// This performs better than calling DrawPolygon multiple times. /// </summary> /// <param name="polygons">The polygons.</param> /// <param name="fill">The fill color. If set to <c>OxyColors.Undefined</c>, the polygons will not be filled.</param> /// <param name="stroke">The stroke color. If set to <c>OxyColors.Undefined</c>, the polygons will not be stroked.</param> /// <param name="thickness">The stroke thickness (in device independent units, 1/96 inch).</param> /// <param name="dashArray">The dash array (in device independent units, 1/96 inch).</param> /// <param name="lineJoin">The line join type.</param> /// <param name="aliased">if set to <c>true</c> the shape will be aliased.</param> public void DrawPolygons( IList <IList <ScreenPoint> > polygons, OxyColor fill, OxyColor stroke, double thickness, double[] dashArray, LineJoin lineJoin, bool aliased) { var usg = UseStreamGeometry; Path path = null; StreamGeometry streamGeometry = null; StreamGeometryContext sgc = null; PathGeometry pathGeometry = null; var count = 0; foreach (var polygon in polygons) { if (path == null) { path = CreateAndAdd <Path>(); SetStroke(path, stroke, thickness, lineJoin, dashArray, 0, aliased); if (!fill.IsUndefined()) { path.Fill = GetCachedBrush(fill); } if (usg) { streamGeometry = new StreamGeometry(); sgc = streamGeometry.Open(); sgc.SetFillRule(FillRule.NonZero); } else { pathGeometry = new PathGeometry { FillRule = FillRule.NonZero }; } } PathFigure figure = null; var first = true; foreach (var p in polygon) { var point = aliased ? ToPixelAlignedPoint(p) : ToPoint(p); if (first) { if (usg) { sgc.BeginFigure(point, !fill.IsUndefined()); } else { figure = new PathFigure { StartPoint = point, IsFilled = !fill.IsUndefined(), IsClosed = true }; pathGeometry.Figures.Add(figure); } first = false; } else { if (usg) { sgc.LineTo(point); } else { figure.Segments.Add(new LineSegment { Point = point }); } } } count++; // Must limit the number of figures, otherwise drawing errors... if (count > MaxFiguresPerGeometry) { if (usg) { sgc.Dispose(); path.Data = streamGeometry; } else { path.Data = pathGeometry; } path = null; count = 0; } } if (path != null) { if (usg) { sgc.Dispose(); path.Data = streamGeometry; } else { path.Data = pathGeometry; } } }
internal void Render(DrawingContext context, GradientBrush tabBackground, double offset) { // Do the horizontal offset first. (tabOuterPath.Transform as TranslateTransform).X = offset; (tabInnerPath.Transform as TranslateTransform).X = offset; Brush outerBrush = new SolidColorBrush(UIColors.CurvyTabOuterColor); context.DrawGeometry(Brushes.White, new Pen(outerBrush, 1), tabOuterPath); Brush innerBrush = new SolidColorBrush(UIColors.CurvyTabInnerColor); context.DrawGeometry(tabBackground, new Pen(innerBrush, 1), tabInnerPath); if (null == formattedText) RefreshFormattedText(); // Finally, draw the display text on the tab. context.DrawText(formattedText, new Point(offset + (parentVisual.GapBetweenTabs + 8), 6)); if (false != parentVisual.ShowCloseButton) { if (null == tabCloseButton) { tabCloseButton = new PathGeometry(); tabCloseButton.Transform = new TranslateTransform(0, 0); tabCloseButton.Figures = CreateButtonPathFigures(); } Brush closeBrush = this.OverCloseButton ? Brushes.Black : Brushes.Gray; double closeOffset = parentVisual.TabWidth + parentVisual.GapBetweenTabs + 2; (tabCloseButton.Transform as TranslateTransform).X = offset + closeOffset; context.DrawGeometry(Brushes.Black, new Pen(closeBrush, 2), tabCloseButton); } }
/// <summary> /// Creates a path geometry from a polygon. /// </summary> public static PathGeometry CreatePolygonGeometry(SysPoint[] points, XFillMode fillMode, bool closed) { PolyLineSegment seg = new PolyLineSegment(); int count = points.Length; // For correct drawing the start point of the segment must not be the same as the first point. for (int idx = 1; idx < count; idx++) seg.Points.Add(new SysPoint(points[idx].X, points[idx].Y)); #if !SILVERLIGHT && !NETFX_CORE seg.IsStroked = true; #endif PathFigure fig = new PathFigure(); fig.StartPoint = new SysPoint(points[0].X, points[0].Y); fig.Segments.Add(seg); fig.IsClosed = closed; PathGeometry geo = new PathGeometry(); geo.FillRule = fillMode == XFillMode.Winding ? FillRule.Nonzero : FillRule.EvenOdd; geo.Figures.Add(fig); return geo; }
/// <summary> /// Draws a Polygon. /// </summary> /// <param name="pen">The Pen.</param> /// <param name="polygon">The Polygon.</param> public void DrawPolygon(Pen pen, Polygon polygon) { var dxPen = pen.Instance as DirectXPen; if (dxPen == null) throw new ArgumentException("DirectX10 expects a DirectXPen as resource."); var geometry = new PathGeometry(DirectXHelper.Direct2DFactory); using (GeometrySink sink = geometry.Open()) { sink.BeginFigure(DirectXHelper.ConvertVector(polygon.Points[0]), FigureBegin.Hollow); for (int i = 1; i < polygon.Points.Length; i++) sink.AddLine(DirectXHelper.ConvertVector(polygon.Points[i])); sink.EndFigure(FigureEnd.Closed); sink.Close(); _renderTarget.DrawGeometry(geometry, dxPen.GetPen(), dxPen.Width); } geometry.Dispose(); }
/// <summary> /// Draws the multiple line segments defined by points (0,1) (2,3) (4,5) etc. /// This should have better performance than calling DrawLine for each segment. /// </summary> /// <param name="points">The points.</param> /// <param name="stroke">The stroke color.</param> /// <param name="thickness">The stroke thickness.</param> /// <param name="dashArray">The dash array.</param> /// <param name="lineJoin">The line join type.</param> /// <param name="aliased">if set to <c>true</c> the shape will be aliased.</param> public void DrawLineSegments( IList<ScreenPoint> points, OxyColor stroke, double thickness, double[] dashArray, OxyPlot.LineJoin lineJoin, bool aliased) { var path = new PathGeometry(this.d2dFactory); var sink = path.Open(); for (int i = 0; i + 1 < points.Count; i += 2) { sink.BeginFigure(points[i].ToVector2(aliased), new FigureBegin()); sink.AddLine(points[i + 1].ToVector2(aliased)); sink.EndFigure(new FigureEnd()); } sink.Close(); sink.Dispose(); var strokeStyle = this.GetStroke(dashArray, lineJoin); this.renderUnits.Add(new GeometryRenderUnit(path, this.GetBrush(stroke), null, (float)thickness, strokeStyle)); }
/// <summary> /// Draws the multiple line segments defined by points (0,1) (2,3) (4,5) etc. /// This should have better performance than calling DrawLine for each segment. /// </summary> /// <param name="points">The points.</param> /// <param name="stroke">The stroke color.</param> /// <param name="thickness">The stroke thickness.</param> /// <param name="dashArray">The dash array.</param> /// <param name="lineJoin">The line join type.</param> /// <param name="aliased">if set to <c>true</c> the shape will be aliased.</param> public void DrawLineSegments( IList<ScreenPoint> points, OxyColor stroke, double thickness, double[] dashArray, LineJoin lineJoin, bool aliased) { var path = new Path(); this.SetStroke(path, stroke, thickness, lineJoin, dashArray, aliased); var pg = new PathGeometry(); for (int i = 0; i + 1 < points.Count; i += 2) { // if (points[i].Y==points[i+1].Y) // { // var line = new Line(); // line.X1 = 0.5+(int)points[i].X; // line.X2 = 0.5+(int)points[i+1].X; // line.Y1 = 0.5+(int)points[i].Y; // line.Y2 = 0.5+(int)points[i+1].Y; // SetStroke(line, OxyColors.DarkRed, thickness, lineJoin, dashArray, aliased); // Add(line); // continue; // } var figure = new PathFigure { StartPoint = points[i].ToPoint(aliased), IsClosed = false }; figure.Segments.Add(new LineSegment { Point = points[i + 1].ToPoint(aliased) }); pg.Figures.Add(figure); } path.Data = pg; this.Add(path); }
protected override void OnCreateDeviceIndependentResources(Direct2DFactory factory) { base.OnCreateDeviceIndependentResources(factory); this._leftMountainGeometry = factory.CreatePathGeometry(); using (GeometrySink sink = this._leftMountainGeometry.Open()) { sink.SetFillMode(FillMode.Winding); sink.BeginFigure(new PointF(346, 255), FigureBegin.Filled); sink.AddLines( new PointF[] { new PointF(267, 177), new PointF(236, 192), new PointF(212, 160), new PointF(156, 255), new PointF(346, 255) }); sink.EndFigure(FigureEnd.Closed); sink.Close(); } this._rightMountainGeometry = factory.CreatePathGeometry(); using (GeometrySink sink = this._rightMountainGeometry.Open()) { sink.SetFillMode(FillMode.Winding); sink.BeginFigure(new PointF(575, 263), FigureBegin.Filled); sink.AddLines( new PointF[] { new PointF(481, 146), new PointF(449, 181), new PointF(433, 159), new PointF(401, 214), new PointF(381, 199), new PointF(323, 263), new PointF(575, 263) }); sink.EndFigure(FigureEnd.Closed); sink.Close(); } this._sunGeometry = factory.CreatePathGeometry(); using (GeometrySink sink = this._sunGeometry.Open()) { sink.SetFillMode(FillMode.Winding); sink.BeginFigure(new PointF(270, 255), FigureBegin.Filled); sink.AddArc( new ArcSegment( new PointF(440, 255), // end point new SizeF(85, 85), 0.0f, // rotation angle SweepDirection.Clockwise, ArcSize.Small)); sink.EndFigure(FigureEnd.Closed); sink.BeginFigure(new PointF(299, 182), FigureBegin.Hollow); sink.AddBezier( new BezierSegment( new PointF(299, 182), new PointF(294, 176), new PointF(285, 178) )); sink.AddBezier( new BezierSegment( new PointF(276, 179), new PointF(272, 173), new PointF(272, 173) )); sink.EndFigure(FigureEnd.Open); sink.BeginFigure( new PointF(354, 156), FigureBegin.Hollow ); sink.AddBezier( new BezierSegment( new PointF(354, 156), new PointF(358, 149), new PointF(354, 142) )); sink.AddBezier( new BezierSegment( new PointF(349, 134), new PointF(354, 127), new PointF(354, 127) )); sink.EndFigure(FigureEnd.Open); sink.BeginFigure( new PointF(322, 164), FigureBegin.Hollow ); sink.AddBezier( new BezierSegment( new PointF(322, 164), new PointF(322, 156), new PointF(314, 152) )); sink.AddBezier( new BezierSegment( new PointF(306, 149), new PointF(305, 141), new PointF(305, 141) )); sink.EndFigure(FigureEnd.Open); sink.BeginFigure( new PointF(385, 164), FigureBegin.Hollow ); sink.AddBezier( new BezierSegment( new PointF(385, 164), new PointF(392, 161), new PointF(394, 152) )); sink.AddBezier( new BezierSegment( new PointF(395, 144), new PointF(402, 141), new PointF(402, 142) )); sink.EndFigure(FigureEnd.Open); sink.BeginFigure( new PointF(408, 182), FigureBegin.Hollow ); sink.AddBezier( new BezierSegment( new PointF(408, 182), new PointF(416, 184), new PointF(422, 178) )); sink.AddBezier( new BezierSegment( new PointF(428, 171), new PointF(435, 173), new PointF(435, 173) )); sink.EndFigure(FigureEnd.Open); sink.Close(); } this._riverGeometry = factory.CreatePathGeometry(); using (GeometrySink sink = this._riverGeometry.Open()) { sink.SetFillMode(FillMode.Winding); sink.BeginFigure( new PointF(183, 392), FigureBegin.Filled ); sink.AddBezier( new BezierSegment( new PointF(238, 284), new PointF(472, 345), new PointF(356, 303) )); sink.AddBezier( new BezierSegment( new PointF(237, 261), new PointF(333, 256), new PointF(333, 256) )); sink.AddBezier( new BezierSegment( new PointF(335, 257), new PointF(241, 261), new PointF(411, 306) )); sink.AddBezier( new BezierSegment( new PointF(574, 350), new PointF(288, 324), new PointF(296, 392) )); sink.EndFigure(FigureEnd.Open); sink.Close(); } }
/// <summary> /// Appends the content of a PathGeometry object. /// </summary> internal void AppendPath(PathGeometry geometry) { const string format = Config.SignificantFigures4; foreach (PathFigure figure in geometry.Figures) { #if DEBUG //#warning For DdlGBE_Chart_Layout (WPF) execution stucks at this Assertion. // The empty Figure is added via XGraphicsPath.CurrentPathFigure Getter. // Some methods like XGraphicsPath.AddRectangle() or AddLine() use this emtpy Figure to add Segments, others like AddEllipse() don't. // Here, _pathGeometry.AddGeometry() of course ignores this first Figure and adds a second. // Encapsulate relevant Add methods to delete a first emty Figure or move the Addition of an first empty Figure to a GetOrCreateCurrentPathFigure() or simply remove Assertion? // Look for: // MAOS4STLA: CurrentPathFigure. if (figure.Segments.Count == 0) 42.GetType(); Debug.Assert(figure.Segments.Count > 0); #endif // Skip the Move if the segment is empty. Workaround for empty segments. Empty segments should not occur (see Debug.Assert above). if (figure.Segments.Count > 0) { // Move to start point. SysPoint currentPoint = figure.StartPoint; AppendFormatPoint("{0:" + format + "} {1:" + format + "} m\n", currentPoint.X, currentPoint.Y); foreach (PathSegment segment in figure.Segments) { Type type = segment.GetType(); if (type == typeof(LineSegment)) { // Draw a single line. SysPoint point = ((LineSegment)segment).Point; currentPoint = point; AppendFormatPoint("{0:" + format + "} {1:" + format + "} l\n", point.X, point.Y); } else if (type == typeof(PolyLineSegment)) { // Draw connected lines. PointCollection points = ((PolyLineSegment)segment).Points; foreach (SysPoint point in points) { currentPoint = point; // I forced myself not to optimize this assignment. AppendFormatPoint("{0:" + format + "} {1:" + format + "} l\n", point.X, point.Y); } } else if (type == typeof(BezierSegment)) { // Draw Bézier curve. BezierSegment seg = (BezierSegment)segment; SysPoint point1 = seg.Point1; SysPoint point2 = seg.Point2; SysPoint point3 = seg.Point3; AppendFormat3Points("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n", point1.X, point1.Y, point2.X, point2.Y, point3.X, point3.Y); currentPoint = point3; } else if (type == typeof(PolyBezierSegment)) { // Draw connected Bézier curves. PointCollection points = ((PolyBezierSegment)segment).Points; int count = points.Count; if (count > 0) { Debug.Assert(count % 3 == 0, "Number of Points in PolyBezierSegment are not a multiple of 3."); for (int idx = 0; idx < count - 2; idx += 3) { SysPoint point1 = points[idx]; SysPoint point2 = points[idx + 1]; SysPoint point3 = points[idx + 2]; AppendFormat3Points("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n", point1.X, point1.Y, point2.X, point2.Y, point3.X, point3.Y); } currentPoint = points[count - 1]; } } else if (type == typeof(ArcSegment)) { // Draw arc. ArcSegment seg = (ArcSegment)segment; AppendPartialArc(currentPoint, seg.Point, seg.RotationAngle, seg.Size, seg.IsLargeArc, seg.SweepDirection, PathStart.Ignore1st); currentPoint = seg.Point; } else if (type == typeof(QuadraticBezierSegment)) { QuadraticBezierSegment seg = (QuadraticBezierSegment)segment; currentPoint = seg.Point2; // TODOWPF: Undone because XGraphics has no such curve type throw new NotImplementedException("AppendPath with QuadraticBezierSegment."); } else if (type == typeof(PolyQuadraticBezierSegment)) { PolyQuadraticBezierSegment seg = (PolyQuadraticBezierSegment)segment; currentPoint = seg.Points[seg.Points.Count - 1]; // TODOWPF: Undone because XGraphics has no such curve type throw new NotImplementedException("AppendPath with PolyQuadraticBezierSegment."); } } if (figure.IsClosed) Append("h\n"); } } }
protected override void OnRender(DrawingContext drawingContext) { bool fading = IsFading && !IsSelected; byte alpha = (byte)(fading ? 80 : 255); this.Fill.Opacity = (double)alpha / 255.0; // Draw highlight first if (m_customEdgeMode) { var circumference = GetRadius() * 2.0 * Math.PI; var edgeStroke = new SolidColorBrush(Color.FromArgb(130, 255, 157, 38)); var edgePen = new Pen(edgeStroke, 30.0); drawingContext.DrawGeometry(edgeStroke, edgePen, m_highLightGeometry); } if (m_highLightGeometry != null && (m_isSelected || m_isHover)) { var edgeStroke = new SolidColorBrush(Color.FromRgb(255, 157, 38)); drawingContext.DrawGeometry(edgeStroke, new Pen(edgeStroke, 10.0), m_highLightGeometry); } base.OnRender(drawingContext); double baseX = 4; double baseY = 0; if (this.m_kind == DoxygenDB.EntKind.VARIABLE) { baseY -= 8; } if (m_displayText != null) { m_displayText.SetForegroundBrush(new SolidColorBrush(Color.FromArgb(alpha, 10, 10, 10))); drawingContext.DrawText(m_displayText, new Point(baseX + 1.0, baseY + 1.0)); m_displayText.SetForegroundBrush(new SolidColorBrush(Color.FromArgb(alpha, 255, 239, 183))); drawingContext.DrawText(m_displayText, new Point(baseX, baseY)); } if (m_commentText != null) { baseY += m_displayText.Height + s_textGap; baseX += 12; m_commentText.SetForegroundBrush(new SolidColorBrush(Color.FromArgb(alpha, 10, 10, 10))); drawingContext.DrawText(m_commentText, new Point(baseX + 0.8, baseY + 0.8)); var commentColor = fading ? Color.FromArgb(alpha, 136, 202, 13) : Color.FromArgb(alpha, 166, 241, 27); m_commentText.SetForegroundBrush(new SolidColorBrush(commentColor)); drawingContext.DrawText(m_commentText, new Point(baseX, baseY)); } if (m_interCustomEdgeMode) { var p0 = new Point(GetRightSlotOffset(), 0); var p3 = Mouse.GetPosition(this); var p1 = new Point(p0.X * 0.5 + p3.X * 0.5, p0.Y); var p2 = new Point(p0.X * 0.5 + p3.X * 0.5, p3.Y); var segment = new BezierSegment(p1, p2, p3, true); var figure = new PathFigure(); figure.StartPoint = p0; figure.Segments.Add(segment); figure.IsClosed = false; var pathGeo = new PathGeometry(); pathGeo.Figures.Add(figure); var pen = new Pen(new SolidColorBrush(Color.FromArgb(100, 255, 255, 255)), 2); drawingContext.DrawGeometry(Brushes.Transparent, pen, pathGeo); } }
/// <summary> /// Refresh the Series Part /// </summary> public override void Refresh() { if (AreaPath != null) { PathFigure figure = new PathFigure(); LineSegment startLineSegment = new LineSegment(); LineSegment areaEndLineSegment = new LineSegment(); LineSegment endLineSegment = new LineSegment(); PathGeometry pathGeometry = new PathGeometry(); figure.StartPoint = StartPoint; startLineSegment.Point = AreaStartPoint; endLineSegment.Point = EndPoint; areaEndLineSegment.Point = AreaEndPoint; figure.Segments.Add(startLineSegment); figure.Segments.Add(areaEndLineSegment); figure.Segments.Add(endLineSegment); pathGeometry.Figures = new PathFigureCollection() { figure }; AreaPath.Data = pathGeometry; } }
void BuildGeometry() { m_geometry = new GeometryGroup(); var r = GetBodyRadius(); if (IsFunction()) { var cosRadian = Math.Cos(20.0 / 180.0 * Math.PI); var sinRadian = Math.Sin(20.0 / 180.0 * Math.PI); var r0 = r; if (m_customData["nCaller"].m_int > 0) { var cr = m_customData["callerR"].m_double; var figure = new PathFigure(); figure.StartPoint = new Point(-r0, 0); figure.Segments.Add(new LineSegment(new Point(-r0 - cr * cosRadian, cr * sinRadian), true)); //figure.Segments.Add(new LineSegment(new Point(-r0 - cr * cosRadian, -sinRadian), true)); figure.Segments.Add(new ArcSegment(new Point(-r0 - cr * cosRadian, cr * -sinRadian), new Size(cr, cr), 0.0, false, SweepDirection.Clockwise, true)); figure.IsClosed = true; figure.IsFilled = true; var pathGeo = new PathGeometry(); pathGeo.Figures.Add(figure); m_geometry.Children.Add(pathGeo); } if (m_customData["nCallee"].m_int > 0) { var cr = m_customData["calleeR"].m_double; var figure = new PathFigure(); figure.StartPoint = new Point(r0, 0); figure.Segments.Add(new LineSegment(new Point(r0 + cr * cosRadian, cr * sinRadian), true)); figure.Segments.Add(new ArcSegment(new Point(r0 + cr * cosRadian, cr * -sinRadian), new Size(cr, cr), 0.0, false, SweepDirection.Counterclockwise, true)); figure.IsClosed = true; figure.IsFilled = true; var pathGeo = new PathGeometry(); pathGeo.Figures.Add(figure); m_geometry.Children.Add(pathGeo); } m_highLightGeometry = new EllipseGeometry(new Point(0.0, 0.0), r, r); if (m_lines == 0 || (m_customData.ContainsKey("hasDef") && m_customData["hasDef"].m_int == 0)) { var innerCircle = new EllipseGeometry(new Point(0.0, 0.0), 1.5, 1.5); m_highLightGeometry = Geometry.Combine(m_highLightGeometry, innerCircle, GeometryCombineMode.Exclude, null); } m_geometry.Children.Add(m_highLightGeometry); } else if (m_kind == DoxygenDB.EntKind.VARIABLE) { var figure = new PathFigure(); figure.StartPoint = new Point(-r, 0.0); figure.Segments.Add(new LineSegment(new Point(r * 0.5, r * 0.85), true)); figure.Segments.Add(new LineSegment(new Point(r * 0.5, -r * 0.85), true)); figure.IsClosed = true; figure.IsFilled = true; var pathGeo = new PathGeometry(); pathGeo.Figures.Add(figure); m_geometry.Children.Add(pathGeo); m_highLightGeometry = pathGeo; } else if (m_kind == DoxygenDB.EntKind.CLASS) { var figure = new PathFigure(); figure.StartPoint = new Point(r, 0.0); figure.Segments.Add(new LineSegment(new Point(0.0, r), true)); figure.Segments.Add(new LineSegment(new Point(-r, 0.0), true)); figure.Segments.Add(new LineSegment(new Point(0.0, -r), true)); figure.IsClosed = true; figure.IsFilled = true; var pathGeo = new PathGeometry(); pathGeo.Figures.Add(figure); m_geometry.Children.Add(pathGeo); m_highLightGeometry = pathGeo; } else if (m_kind == DoxygenDB.EntKind.FILE) { var rect = new RectangleGeometry(new Rect(new Point(-r, -r), new Point(r, r))); m_geometry.Children.Add(rect); m_highLightGeometry = rect; } else if (m_kind == DoxygenDB.EntKind.DIR) { var figure = new PathFigure(); figure.StartPoint = new Point(r, r); figure.Segments.Add(new LineSegment(new Point(-r, r), true)); figure.Segments.Add(new LineSegment(new Point(-r, -r * 0.6), true)); figure.Segments.Add(new LineSegment(new Point(-r * 0.8, -r), true)); figure.Segments.Add(new LineSegment(new Point(r * 0.2, -r), true)); figure.Segments.Add(new LineSegment(new Point(r * 0.4, -r * 0.6), true)); figure.Segments.Add(new LineSegment(new Point(r, -r * 0.6), true)); figure.IsClosed = true; figure.IsFilled = true; var pathGeo = new PathGeometry(); pathGeo.Figures.Add(figure); m_geometry.Children.Add(pathGeo); m_highLightGeometry = pathGeo; } else { float w = 3.0f; var pathGeo = new PathGeometry(); var figure = new PathFigure(); figure.StartPoint = new Point(w, w); figure.Segments.Add(new LineSegment(new Point(-w, -w), true)); figure.IsClosed = false; figure.IsFilled = false; pathGeo.Figures.Add(figure); figure = new PathFigure(); figure.StartPoint = new Point(w, -w); figure.Segments.Add(new LineSegment(new Point(-w, w), true)); figure.IsClosed = false; figure.IsFilled = false; pathGeo.Figures.Add(figure); var outlinePen = new Pen(); outlinePen.Thickness = 2.0; outlinePen.LineJoin = PenLineJoin.Round; pathGeo = pathGeo.GetWidenedPathGeometry(outlinePen).GetOutlinedPathGeometry(); m_geometry.Children.Add(pathGeo); m_highLightGeometry = pathGeo; } }
private void UpdateChart() { double maxHorizontal = graphSize.Width; List <double> values = this.pending; this.pending = new List <double>(); if (sizeChanged) { Reset(); SetupGridLines(); values = Tail(this.history, (int)maxHorizontal); sizeChanged = false; } double shadowYOffset = ShadowDepth; double shadowXOffset = -ShadowDepth / 2; HashSet <Path> modified = new HashSet <Path>(); foreach (double v in values) { Path lineGraph = GetOrCreateActiveLineGraph(); Path shadowLineGraph = GetOrCreateActiveShadowLineGraph(); if (lineGraph.Data == null) { lineGraph.Data = new PathGeometry(); } if (shadowLineGraph.Data == null) { shadowLineGraph.Data = new PathGeometry(); } modified.Add(lineGraph); modified.Add(shadowLineGraph); PathGeometry g = (PathGeometry)lineGraph.Data; PathGeometry sg = (PathGeometry)shadowLineGraph.Data; PathFigure f = g.Figures.FirstOrDefault(); PathFigure sf = sg.Figures.FirstOrDefault(); Point minLabelPos = new Point(-100, 0); Point maxLabelPos = new Point(-100, 0); Point minLabelConnector = new Point(-100, 0); Point maxLabelConnector = new Point(-100, 0); double height = graphSize.Height; double min = this.Minimum; double max = this.Maximum; double range = (max - min); if (range == 0) { range = 1; } // add the new values to the path double value = v; double y = height - ((value - min) * height / range); if (f == null) { f = new PathFigure() { StartPoint = new Point(x, y), IsFilled = false, IsClosed = false }; g.Figures.Add(f); } else { f.Segments.Add(new LineSegment() { Point = new Point(x, y) }); } // shadow if (sf == null) { sf = new PathFigure() { StartPoint = new Point(x + shadowXOffset, y + shadowYOffset), IsFilled = false, IsClosed = false }; sg.Figures.Add(sf); } else { sf.Segments.Add(new LineSegment() { Point = new Point(x + shadowXOffset, y + shadowYOffset) }); } x++; totalX++; if (f.Segments.Count > MaxLineGraphLength) { x = 0; activeLineGraph = null; activeShadowLineGraph = null; } } // reassign the data to force a visual update. foreach (Path path in modified) { path.Data = path.Data; } }
private void Run_Click(object sender, RoutedEventArgs e) { var VMCountriesPartStyle = "VM_CountriesPartStyle"; var binding = new Binding(VMCountriesPartStyle) { Mode = BindingMode.OneWay }; this.SetBinding(CountriesPartStyleProperty, binding); float pieWidth = 250, pieHeight = 250, centerX = pieWidth / 2, centerY = pieHeight / 2, radius = pieWidth / 2; mainCanvas.Width = pieWidth; mainCanvas.Height = pieHeight; Categories = new List <Category>(); List <SolidColorBrush> colors = new List <SolidColorBrush> { new SolidColorBrush((Color)ColorConverter.ConvertFromString("#80bfff")), // blue new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ff99cc")), // pink new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ffcc99")), // orenge new SolidColorBrush((Color)ColorConverter.ConvertFromString("#66ff66")), // green new SolidColorBrush((Color)ColorConverter.ConvertFromString("#d9b3ff")), // perpul }; int i = 0; foreach (KeyValuePair <string, int> entry in CountriesPartStyle) { Category category = new Category { Title = entry.Key, Percentage = entry.Value, ColorBrush = colors[i], }; Categories.Add(category); i++; // Check witch country is the country with the biggest Percentage. if (entry.Value > maxPart) { maxPart = entry.Value; contryResult = entry.Key; color = colors[i - 1].ToString(); } } detailsItemsControl.ItemsSource = Categories; // Draw pie float angle = 0, prevAngle = 0; foreach (var category in Categories) { double line1X = (radius * Math.Cos(angle * Math.PI / 180)) + centerX; double line1Y = (radius * Math.Sin(angle * Math.PI / 180)) + centerY; angle = category.Percentage * (float)360 / 100 + prevAngle; Debug.WriteLine(angle); double arcX = (radius * Math.Cos(angle * Math.PI / 180)) + centerX; double arcY = (radius * Math.Sin(angle * Math.PI / 180)) + centerY; var line1Segment = new LineSegment(new Point(line1X, line1Y), false); double arcWidth = radius, arcHeight = radius; bool isLargeArc = category.Percentage > 50; var arcSegment = new ArcSegment() { Size = new Size(arcWidth, arcHeight), Point = new Point(arcX, arcY), SweepDirection = SweepDirection.Clockwise, IsLargeArc = isLargeArc, }; var line2Segment = new LineSegment(new Point(centerX, centerY), false); var pathFigure = new PathFigure( new Point(centerX, centerY), new List <PathSegment>() { line1Segment, arcSegment, line2Segment, }, true); var pathFigures = new List <PathFigure>() { pathFigure, }; var pathGeometry = new PathGeometry(pathFigures); var path = new Path() { Fill = category.ColorBrush, Data = pathGeometry, }; mainCanvas.Children.Add(path); prevAngle = angle; // Draw outlines var outline1 = new Line() { X1 = centerX, Y1 = centerY, X2 = line1Segment.Point.X, Y2 = line1Segment.Point.Y, Stroke = Brushes.White, StrokeThickness = 5, }; var outline2 = new Line() { X1 = centerX, Y1 = centerY, X2 = arcSegment.Point.X, Y2 = arcSegment.Point.Y, Stroke = Brushes.White, StrokeThickness = 5, }; mainCanvas.Children.Add(outline1); mainCanvas.Children.Add(outline2); } // Update result view. resultsView.Visibility = Visibility.Visible; resultVal.Text = contryResult; resultVal.Background = new BrushConverter().ConvertFromString(color) as SolidColorBrush; maxPart = 0; }
ShapeData DoArc(float cx, float cy, float radius, float startAngle, float endAngle) { var s = GetNextShape (TypeId.Arc); var e = s.Element as Path; if (e.Data == null || s.X != cx || s.Y != cy || s.Radius != radius || s.Width != startAngle || s.Height != endAngle) { s.X = cx; s.Y = cy; s.Radius = radius; s.Width = startAngle; s.Height = endAngle; var fig = new PathFigure(); var sa = -startAngle; var ea = -endAngle; fig.StartPoint = new Point( cx + radius * Math.Cos(sa), cy + radius * Math.Sin(sa)); fig.Segments.Add(new ArcSegment() { Point = new Point( cx + radius * Math.Cos(ea), cy + radius * Math.Sin(ea)), Size = new Size(radius, radius), SweepDirection = SweepDirection.Counterclockwise, }); var geo = new PathGeometry(); geo.Figures.Add(fig); e.Data = geo; } return s; }
/// <summary> /// Actually creates the visual appearance of a node. /// </summary> /// <remarks> /// This renders the node and the edges to the labels and adds the visuals to the <paramref name="container"/>. /// All items are arranged as if the node was located at (0,0). <see cref="CreateVisual"/> and /// <see cref="IVisualCreator.UpdateVisual"/> finally arrange the container so that the drawing is translated into /// the final position. /// </remarks> private void Render(IRenderContext context, INode node, VisualGroup container) { // the size of node SizeD nodeSize = node.Layout.ToSizeD(); Ellipse shape = new Ellipse { Width = nodeSize.Width, Height = nodeSize.Height, Effect = new DropShadowEffect() { BlurRadius = 3, Color = Colors.Black, Opacity = 0.2, ShadowDepth = 3 } }; // max and min needed for reflection effect calculation double max = Math.Max(nodeSize.Width, nodeSize.Height); double min = Math.Min(nodeSize.Width, nodeSize.Height); // Create Background gradient from specified background color shape.Fill = new LinearGradientBrush { GradientStops = { gradientStop1, gradientStop2, gradientStop3 }, StartPoint = new Point(0, 0), EndPoint = new Point(0.5 / (nodeSize.Width / max), 1 / (nodeSize.Height / max)), SpreadMethod = GradientSpreadMethod.Pad }; // Create light reflection effects Ellipse reflection1 = new Ellipse { Width = min / 10, Height = min / 10, Fill = Brushes.White }; Ellipse reflection2 = new Ellipse { Width = min / 7, Height = min / 7, Fill = Brushes.AliceBlue }; PathGeometry reflection3 = new PathGeometry(); PathFigure figure = new PathFigure(); Point startPoint = new Point(nodeSize.Width / 2.5, nodeSize.Height / 10 * 9); Point endPoint = new Point(nodeSize.Width / 10 * 9, nodeSize.Height / 2.5); Point ctrlPoint1 = new Point(startPoint.X + (endPoint.X - startPoint.X) / 2, nodeSize.Height); Point ctrlPoint2 = new Point(nodeSize.Width, startPoint.Y + (endPoint.Y - startPoint.Y) / 2); Point ctrlPoint3 = new Point(ctrlPoint1.X, ctrlPoint1.Y - nodeSize.Height / 10); Point ctrlPoint4 = new Point(ctrlPoint2.X - nodeSize.Width / 10, ctrlPoint2.Y); figure.StartPoint = startPoint; reflection3.Figures.Add(figure); figure.Segments.Add(new BezierSegment { Point1 = ctrlPoint1, Point2 = ctrlPoint2, Point3 = endPoint }); figure.Segments.Add(new BezierSegment { Point1 = ctrlPoint4, Point2 = ctrlPoint3, Point3 = startPoint }); figure.IsFilled = true; Path p = new Path(); p.Data = reflection3; p.Fill = Brushes.AliceBlue; figure.Freeze(); // place the reflections reflection1.SetCanvasArrangeRect(new Rect(nodeSize.Width / 5, nodeSize.Height / 5, min / 10, min / 10)); reflection2.SetCanvasArrangeRect(new Rect(nodeSize.Width / 4.9, nodeSize.Height / 4.9, min / 7, min / 7)); // and add all to the container for the node container.Children.Add(shape); container.Children.Add(reflection2); container.Children.Add(reflection1); container.Children.Add(p); }
/// <summary> /// Draws a collection of polygons, where all polygons have the same stroke and fill. /// This performs better than calling DrawPolygon multiple times. /// </summary> /// <param name="polygons">The polygons.</param> /// <param name="fill">The fill color.</param> /// <param name="stroke">The stroke color.</param> /// <param name="thickness">The stroke thickness.</param> /// <param name="dashArray">The dash array.</param> /// <param name="lineJoin">The line join type.</param> /// <param name="aliased">if set to <c>true</c> the shape will be aliased.</param> public void DrawPolygons( IList<IList<ScreenPoint>> polygons, OxyColor fill, OxyColor stroke, double thickness, double[] dashArray, OxyPlot.LineJoin lineJoin, bool aliased) { var path = new PathGeometry(this.d2dFactory); var sink = path.Open(); foreach (var points in polygons) { sink.BeginFigure(points[0].ToVector2(aliased), new FigureBegin()); sink.AddLines(points.Skip(1).Select(pt => (dx.Mathematics.Interop.RawVector2)pt.ToVector2(aliased)).ToArray()); sink.EndFigure(new FigureEnd()); } sink.Close(); sink.Dispose(); var strokeStyle = this.GetStroke(dashArray, lineJoin); this.renderUnits.Add(new GeometryRenderUnit(path, this.GetBrush(stroke), this.GetBrush(fill), (float)thickness, strokeStyle)); }
DrawingGroup LoadGroup(IList <Shape> elements) { List <ControlLine> debugPoints = new List <ControlLine>(); DrawingGroup grp = new DrawingGroup(); foreach (ClipArtViewer.Shape shape in elements) { if (shape is ClipArtViewer.UseShape) { ClipArtViewer.UseShape useshape = shape as ClipArtViewer.UseShape; ClipArtViewer.Group group = SVG.GetShape(useshape.hRef) as ClipArtViewer.Group; if (group != null) { Shape oldparent = group.Parent; group.Parent = useshape; // this to get proper style propagated DrawingGroup subgroup = LoadGroup(group.Elements); subgroup.Transform = new TranslateTransform(useshape.X, useshape.Y); grp.Children.Add(subgroup); group.Parent = oldparent; } continue; } if (shape is ClipArtViewer.Group) { DrawingGroup subgroup = LoadGroup((shape as ClipArtViewer.Group).Elements); if (shape.Transform != null) { subgroup.Transform = shape.Transform; } grp.Children.Add(subgroup); continue; } if (shape is ClipArtViewer.RectangleShape) { ClipArtViewer.RectangleShape r = shape as ClipArtViewer.RectangleShape; RectangleGeometry rect = new RectangleGeometry(new Rect(r.X, r.Y, r.Width, r.Height)); rect.RadiusX = r.RX; rect.RadiusY = r.RY; if (rect.RadiusX == 0 && rect.RadiusY > 0) { rect.RadiusX = rect.RadiusY; } grp.Children.Add(NewDrawingItem(shape, rect)); } if (shape is ClipArtViewer.LineShape) { ClipArtViewer.LineShape r = shape as ClipArtViewer.LineShape; LineGeometry line = new LineGeometry(r.P1, r.P2); grp.Children.Add(NewDrawingItem(shape, line)); } if (shape is ClipArtViewer.PolylineShape) { ClipArtViewer.PolylineShape r = shape as ClipArtViewer.PolylineShape; PathGeometry path = new PathGeometry(); PathFigure p = new PathFigure(); path.Figures.Add(p); p.IsClosed = false; p.StartPoint = r.Points[0]; for (int index = 1; index < r.Points.Length; index++) { p.Segments.Add(new LineSegment(r.Points[index], true)); } grp.Children.Add(NewDrawingItem(shape, path)); } if (shape is ClipArtViewer.PolygonShape) { ClipArtViewer.PolygonShape r = shape as ClipArtViewer.PolygonShape; PathGeometry path = new PathGeometry(); PathFigure p = new PathFigure(); path.Figures.Add(p); p.IsClosed = true; p.StartPoint = r.Points[0]; for (int index = 1; index < r.Points.Length; index++) { p.Segments.Add(new LineSegment(r.Points[index], true)); } grp.Children.Add(NewDrawingItem(shape, path)); } if (shape is ClipArtViewer.CircleShape) { ClipArtViewer.CircleShape r = shape as ClipArtViewer.CircleShape; EllipseGeometry c = new EllipseGeometry(new Point(r.CX, r.CY), r.R, r.R); grp.Children.Add(NewDrawingItem(shape, c)); } if (shape is ClipArtViewer.EllipseShape) { ClipArtViewer.EllipseShape r = shape as ClipArtViewer.EllipseShape; EllipseGeometry c = new EllipseGeometry(new Point(r.CX, r.CY), r.RX, r.RY); grp.Children.Add(NewDrawingItem(shape, c)); } if (shape is ClipArtViewer.ImageShape) { ClipArtViewer.ImageShape image = shape as ClipArtViewer.ImageShape; ImageDrawing i = new ImageDrawing(image.ImageSource, new Rect(image.X, image.Y, image.Width, image.Height)); grp.Children.Add(i); } if (shape is ClipArtViewer.TextShape) { GeometryGroup gp = TextRender.BuildTextGeometry(shape as ClipArtViewer.TextShape); if (gp != null) { foreach (Geometry gm in gp.Children) { TextShape.TSpan.Element tspan = TextRender.GetElement(gm); if (tspan != null) { grp.Children.Add(NewDrawingItem(tspan, gm)); } else { grp.Children.Add(NewDrawingItem(shape, gm)); } } } } if (shape is ClipArtViewer.PathShape) { ClipArtViewer.PathShape r = shape as ClipArtViewer.PathShape; PathFigure p = null; Point lastPoint = new Point(0, 0); ClipArtViewer.PathShape.CurveTo lastc = null; Point lastcirPoint = new Point(0, 0); PathGeometry path = new PathGeometry(); foreach (ClipArtViewer.PathShape.PathElement element in r.Elements) { bool isRelative = element.IsRelative; if (element is ClipArtViewer.PathShape.MoveTo) { p = new PathFigure(); p.IsClosed = r.ClosePath; if (isRelative) { p.StartPoint = lastPoint + (Vector)((ClipArtViewer.PathShape.MoveTo)element).Point; } else { p.StartPoint = ((ClipArtViewer.PathShape.MoveTo)element).Point; } lastPoint = p.StartPoint; path.Figures.Add(p); continue; } if (element is ClipArtViewer.PathShape.LineTo) { ClipArtViewer.PathShape.LineTo lineto = element as ClipArtViewer.PathShape.LineTo; foreach (Point point in lineto.Points) { if (isRelative) { Point newpoint = lastPoint + (Vector)point; lastPoint = newpoint; p.Segments.Add(new LineSegment(newpoint, true)); } else { if (lineto.PositionType == PathShape.LineTo.eType.Point) { lastPoint = point; } if (lineto.PositionType == PathShape.LineTo.eType.Horizontal) { lastPoint = new Point(point.X, lastPoint.Y); } if (lineto.PositionType == PathShape.LineTo.eType.Vertical) { lastPoint = new Point(lastPoint.X, point.Y); } p.Segments.Add(new LineSegment(lastPoint, true)); } } continue; } if (element is ClipArtViewer.PathShape.CurveTo) { ClipArtViewer.PathShape.CurveTo c = element as ClipArtViewer.PathShape.CurveTo; Point startPoint = lastPoint; BezierSegment s = new BezierSegment(); if (isRelative) { s.Point1 = lastPoint + (Vector)c.CtrlPoint1; if (c.Command == 's') { // first control point is a mirrored point of last end control point //s.Point1 = lastPoint + new Vector(lastc.Point.X - dx, lastc.Point.Y - dy); //s.Point1 = new Point(lastctrlpoint.X+2, lastctrlpoint.Y+2); double dx = lastc.CtrlPoint2.X - lastc.Point.X; double dy = lastc.CtrlPoint2.Y - lastc.Point.Y; s.Point1 = new Point(lastcirPoint.X - dx, lastcirPoint.Y - dy); //s.Point1 = lastctrlpoint; } s.Point2 = lastPoint + (Vector)c.CtrlPoint2; s.Point3 = lastPoint + (Vector)c.Point; } else { s.Point1 = c.CtrlPoint1; s.Point2 = c.CtrlPoint2; s.Point3 = c.Point; } lastPoint = s.Point3; p.Segments.Add(s); lastc = c; lastcirPoint = s.Point3; //debugPoints.Add(new ControlLine(startPoint, s.Point1)); //debugPoints.Add(new ControlLine(s.Point3, s.Point2)); continue; } if (element is ClipArtViewer.PathShape.EllipticalArcTo) { ClipArtViewer.PathShape.EllipticalArcTo c = element as ClipArtViewer.PathShape.EllipticalArcTo; ArcSegment s = new ArcSegment(); if (isRelative) { s.Point = lastPoint + new Vector(c.X, c.Y); } else { s.Point = new Point(c.X, c.Y); } s.Size = new Size(c.RX, c.RY); s.RotationAngle = c.AxisRotation; s.SweepDirection = SweepDirection.Counterclockwise; if (c.Clockwise) { s.SweepDirection = SweepDirection.Clockwise; } s.IsLargeArc = c.LargeArc; lastPoint = s.Point; p.Segments.Add(s); continue; } } /* * if (r.Transform != null) * path.Transform = r.Transform; */ grp.Children.Add(NewDrawingItem(shape, path)); //} } } if (debugPoints != null) { foreach (ControlLine line in debugPoints) { grp.Children.Add(line.Draw()); } } return(grp); }
private void DrawFunnelFigure(FixedContentEditor editor) { editor.GraphicProperties.IsStroked = false; editor.GraphicProperties.FillColor = new RgbColor(231, 238, 247); editor.DrawEllipse(new Point(250, 70), 136, 48); editor.GraphicProperties.IsStroked = true; editor.GraphicProperties.StrokeColor = RgbColors.White; editor.GraphicProperties.StrokeThickness = 1; editor.GraphicProperties.FillColor = new RgbColor(91, 155, 223); editor.DrawEllipse(new Point(289, 77), 48, 48); editor.Position.Translate(291, 204); CenterText(editor, "Fonts"); editor.Position.Translate(0, 0); editor.DrawEllipse(new Point(238, 274), 48, 48); editor.Position.Translate(190, 226); CenterText(editor, "Images"); editor.Position.Translate(0, 0); editor.DrawEllipse(new Point(307, 347), 48, 48); editor.Position.Translate(259, 299); CenterText(editor, "Shapes"); editor.Position.Translate(0, 0); PathGeometry arrow = new PathGeometry(); PathFigure figure = arrow.Figures.AddPathFigure(); figure.StartPoint = new Point(287, 422); figure.IsClosed = true; figure.Segments.AddLineSegment(new Point(287, 438)); figure.Segments.AddLineSegment(new Point(278, 438)); figure.Segments.AddLineSegment(new Point(300, 454)); figure.Segments.AddLineSegment(new Point(322, 438)); figure.Segments.AddLineSegment(new Point(313, 438)); figure.Segments.AddLineSegment(new Point(313, 422)); editor.DrawPath(arrow); editor.GraphicProperties.FillColor = new RgbColor(80, 255, 255, 255); editor.GraphicProperties.IsStroked = true; editor.GraphicProperties.StrokeThickness = 1; editor.GraphicProperties.StrokeColor = new RgbColor(91, 155, 223); PathGeometry funnel = new PathGeometry(); funnel.FillRule = FillRule.EvenOdd; figure = funnel.Figures.AddPathFigure(); figure.IsClosed = true; figure.StartPoint = new Point(164, 245); figure.Segments.AddArcSegment(new Point(436, 245), 136, 48); figure.Segments.AddArcSegment(new Point(164, 245), 136, 48); figure = funnel.Figures.AddPathFigure(); figure.IsClosed = true; figure.StartPoint = new Point(151, 245); figure.Segments.AddArcSegment(new Point(449, 245), 149, 61); figure.Segments.AddLineSegment(new Point(332, 415)); figure.Segments.AddArcSegment(new Point(268, 415), 16, 4); editor.DrawPath(funnel); editor.Position.Translate(164, 455); Block block = new Block(); block.TextProperties.Font = editor.TextProperties.Font; block.GraphicProperties.FillColor = RgbColors.Black; block.HorizontalAlignment = HorizontalAlignment.Center; block.VerticalAlignment = VerticalAlignment.Top; block.TextProperties.FontSize = 18; block.InsertText("PDF"); editor.DrawBlock(block, new Size(272, double.PositiveInfinity)); }
// animation: private Storyboard IntilaizeStory(Point start, Point end, long colorID) { // Create a NameScope for the page so that // we can use Storyboards. NameScope.SetNameScope(PublicParameters.MainWindow.Canvas_SensingFeild, new NameScope()); // Create a rectangle. Border aRectangle = new Border(); aRectangle.CornerRadius = new CornerRadius(2); aRectangle.Width = 7; aRectangle.Height = 7; int cid = Convert.ToInt16(colorID % PublicParameters.RandomColors.Count); aRectangle.Background = new SolidColorBrush(PublicParameters.RandomColors[cid]); aRectangle.BorderThickness = new Thickness(1); aRectangle.BorderBrush = new SolidColorBrush(Colors.Black); MovedObjectStack.Push(aRectangle); // Create a transform. This transform // will be used to move the rectangle. TranslateTransform animatedTranslateTransform = new TranslateTransform(); // Register the transform's name with the page // so that they it be targeted by a Storyboard. PublicParameters.MainWindow.Canvas_SensingFeild.RegisterName("AnimatedTranslateTransform", animatedTranslateTransform); aRectangle.RenderTransform = animatedTranslateTransform; PublicParameters.MainWindow.Canvas_SensingFeild.Children.Add(aRectangle); // Create the animation path. PathGeometry animationPath = new PathGeometry(); PathFigure pFigure = new PathFigure(); // add the figure. pFigure.StartPoint = start; // define the start point of the Figure. LineSegment lineSegment = new LineSegment(); // move according to line. lineSegment.Point = end; // set the end point. pFigure.Segments.Add(lineSegment); // add the line to the figure. animationPath.Figures.Add(pFigure); // add the figure to the path. // Freeze the PathGeometry for performance benefits. animationPath.Freeze(); // Create a DoubleAnimationUsingPath to move the // rectangle horizontally along the path by animating // its TranslateTransform. DoubleAnimationUsingPath translateXAnimation = new DoubleAnimationUsingPath(); translateXAnimation.PathGeometry = animationPath; translateXAnimation.Duration = TimeSpan.FromSeconds(Properties.Settings.Default.AnimationSpeed); // Set the Source property to X. This makes // the animation generate horizontal offset values from // the path information. translateXAnimation.Source = PathAnimationSource.X; // Set the animation to target the X property // of the TranslateTransform named "AnimatedTranslateTransform". Storyboard.SetTargetName(translateXAnimation, "AnimatedTranslateTransform"); Storyboard.SetTargetProperty(translateXAnimation, new PropertyPath(TranslateTransform.XProperty)); // Create a DoubleAnimationUsingPath to move the // rectangle vertically along the path by animating // its TranslateTransform. DoubleAnimationUsingPath translateYAnimation = new DoubleAnimationUsingPath(); translateYAnimation.PathGeometry = animationPath; translateYAnimation.Duration = TimeSpan.FromSeconds(Properties.Settings.Default.AnimationSpeed); // Set the Source property to Y. This makes // the animation generate vertical offset values from // the path information. translateYAnimation.Source = PathAnimationSource.Y; // Set the animation to target the Y property // of the TranslateTransform named "AnimatedTranslateTransform". Storyboard.SetTargetName(translateYAnimation, "AnimatedTranslateTransform"); Storyboard.SetTargetProperty(translateYAnimation, new PropertyPath(TranslateTransform.YProperty)); // Create a Storyboard to contain and apply the animations. Storyboard pathAnimationStoryboard = new Storyboard(); //pathAnimationStoryboard.RepeatBehavior = RepeatBehavior.Forever; pathAnimationStoryboard.Children.Add(translateXAnimation); pathAnimationStoryboard.Children.Add(translateYAnimation); return(pathAnimationStoryboard); }
public void DrawArc(float cx, float cy, float radius, float startAngle, float endAngle, float w) { var s = GetNextShape(TypeId.Arc); var e = s.Element as Path; if (e.Data == null || s.X != cx || s.Y != cy || s.Radius != radius || s.Width != startAngle || s.Height != endAngle) { s.X = cx; s.Y = cy; s.Radius = radius; s.Width = startAngle; s.Height = endAngle; var fig = new PathFigure(); var sa = -startAngle; var ea = -endAngle; fig.StartPoint = new Point( cx + radius * Math.Cos(sa), cy + radius * Math.Sin(sa)); fig.Segments.Add(new ArcSegment() { Point = new Point( cx + radius * Math.Cos(ea), cy + radius * Math.Sin(ea)), Size = new Size(radius, radius), SweepDirection = SweepDirection.Counterclockwise, }); var geo = new PathGeometry(); geo.Figures.Add(fig); e.Data = geo; } if (s.Thickness != w) { s.Thickness = w; e.StrokeThickness = w; } if (s.Color != _currentColor || s.DrawOp != DrawOp.Draw) { s.Color = _currentColor; s.DrawOp = DrawOp.Draw; e.Stroke = _currentColor.GetBrush(); e.Fill = null; } }
private static Geometry ProcessPathData(List<PathInfo> pis) { PathGeometry geometry = new PathGeometry(); PathFigure figure = null; foreach (var pi in pis) { switch (pi.segmentType) { case SegmentType.Move: figure = new PathFigure() { StartPoint = pi.point }; geometry.Figures.Add(figure); break; case SegmentType.Line: figure.Segments.Add(new LineSegment() { Point = pi.point }); break; case SegmentType.Arc: figure.Segments.Add(new ArcSegment() { Size = new Size(pi.size.X, pi.size.Y), IsLargeArc = pi.isLargeArc, Point = pi.point, RotationAngle = pi.angle, SweepDirection = pi.isSweepDirectionClockwise ? SweepDirection.Clockwise : SweepDirection.Counterclockwise }); break; case SegmentType.Close: figure.IsClosed = true; break; default: break; } } return geometry; }
public PathGeometry CloneDeep(PathGeometry pathGeometry) { var newPathGeometry = new PathGeometry(); foreach (var figure in pathGeometry.Figures) { var newFigure = new PathFigure(); newFigure.StartPoint = figure.StartPoint; // Even figures have to be deep cloned. Assigning them directly will result in // an InvalidOperationException being thrown with the message "Element is already the child of another element." foreach (var segment in figure.Segments) { // I only impemented cloning the abstract PathSegments to one implementation, // the PolyLineSegment class. If your paths use other kinds of segments, you'll need // to implement that kind of coding yourself. var segmentAsPolyLineSegment = segment as PolyLineSegment; if (segmentAsPolyLineSegment != null) { var newSegment = new PolyLineSegment(); foreach (var point in segmentAsPolyLineSegment.Points) { newSegment.Points.Add(point); } newFigure.Segments.Add(newSegment); } var segmentAsLineSegment = segment as LineSegment; if (segmentAsLineSegment != null) { var newSegment = new LineSegment(); newSegment.Point = segmentAsLineSegment.Point; newFigure.Segments.Add(newSegment); } var segmentAsArcSegment = segment as ArcSegment; if (segmentAsArcSegment != null) { var newSegment = new ArcSegment(); newSegment.Point = segmentAsArcSegment.Point; newSegment.SweepDirection = segmentAsArcSegment.SweepDirection; newSegment.RotationAngle = segmentAsArcSegment.RotationAngle; newSegment.IsLargeArc = segmentAsArcSegment.IsLargeArc; newSegment.Size = segmentAsArcSegment.Size; newFigure.Segments.Add(newSegment); } } newPathGeometry.Figures.Add(newFigure); } return newPathGeometry; }