コード例 #1
0
ファイル: EntryArrow.cs プロジェクト: etkraw/Microwalk
        /// <summary>
        /// Creates an arrow drawing.
        /// </summary>
        /// <param name="selected">Sets whether the arrow should be highlighted.</param>
        /// <returns></returns>
        private DrawingVisual CreateArrowVisual(bool selected)
        {
            // Start drawing
            DrawingVisual  drawing        = new DrawingVisual();
            DrawingContext drawingContext = drawing.RenderOpen();

            // Derive style by branch type
            Brush brush   = Brushes.Gray;
            Pen   linePen = new Pen(Brushes.Gray, 2);

            if (TraceFileEntry.BranchType == BranchTypes.Call)
            {
                // Solid blue line
                if (TraceFileId == 1)
                {
                    brush   = Brushes.Blue;
                    linePen = new Pen(Brushes.Blue, 2);
                }
                else if (TraceFileId == 2)
                {
                    brush   = Brushes.Firebrick;
                    linePen = new Pen(Brushes.Firebrick, 2);
                }
            }
            else if (TraceFileEntry.BranchType == BranchTypes.Ret)
            {
                // Dashed blue line
                if (TraceFileId == 1)
                {
                    brush   = Brushes.Blue;
                    linePen = new Pen(Brushes.Blue, 2)
                    {
                        DashStyle = DashStyles.Dash
                    };
                }
                else if (TraceFileId == 2)
                {
                    brush   = Brushes.Firebrick;
                    linePen = new Pen(Brushes.Firebrick, 2)
                    {
                        DashStyle = DashStyles.Dash
                    };
                }
            }
            else // Jump
            {
                // Solid red line
                if (TraceFileId == 1)
                {
                    brush   = Brushes.RoyalBlue;
                    linePen = new Pen(Brushes.RoyalBlue, 2);
                }
                else if (TraceFileId == 2)
                {
                    brush   = Brushes.Red;
                    linePen = new Pen(Brushes.Red, 2);
                }
            }

            // Highlight?
            if (selected)
            {
                linePen.Thickness = 4;
            }

            // Draw arrows for non-function internal branches, else boxes
            if (From != To)
            {
                // Prepare arrow head
                Point          arrowTipPosition = new Point(To.CenterXPosition - From.CenterXPosition, ArrowTipSideLength / 2);
                Point          p1       = new Point(arrowTipPosition.X > 0 ? arrowTipPosition.X - ArrowTipSideLength : arrowTipPosition.X + ArrowTipSideLength, arrowTipPosition.Y - ArrowTipSideLength / 2);
                Point          p2       = new Point(arrowTipPosition.X > 0 ? arrowTipPosition.X - ArrowTipSideLength : arrowTipPosition.X + ArrowTipSideLength, arrowTipPosition.Y + ArrowTipSideLength / 2);
                Point          p3       = new Point(arrowTipPosition.X, arrowTipPosition.Y);
                StreamGeometry arrowTip = new StreamGeometry();
                using (StreamGeometryContext geometryContext = arrowTip.Open())
                {
                    geometryContext.BeginFigure(p1, true, true);
                    geometryContext.PolyLineTo(new PointCollection {
                        p2, p3
                    }, true, true);
                }
                arrowTip.Freeze();

                // Draw arrow (line is slightly shorter that needed, to prevent it from distorting the arrow tip)
                double lineLength = To.CenterXPosition - From.CenterXPosition + (arrowTipPosition.X > 0 ? -ArrowTipSideLength / 2 : ArrowTipSideLength / 2);
                drawingContext.DrawLine(linePen, new Point(0, ArrowTipSideLength / 2), new Point(lineLength, ArrowTipSideLength / 2));
                drawingContext.DrawGeometry(brush, new Pen(brush, 1), arrowTip);
            }
            else
            {
                // Draw filled rectangle
                drawingContext.DrawRectangle(brush, linePen, new Rect(-ArrowTipSideLength, 0, 2 * ArrowTipSideLength, ArrowTipSideLength));
            }

            // Finish drawing
            drawingContext.Close();
            return(drawing);
        }
コード例 #2
0
        /// <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            = this.UseStreamGeometry;
            Path                  path           = null;
            StreamGeometry        streamGeometry = null;
            StreamGeometryContext sgc            = null;
            PathGeometry          pathGeometry   = null;
            int                   count          = 0;

            foreach (var polygon in polygons)
            {
                if (path == null)
                {
                    path = this.CreateAndAdd <Path>();
                    this.SetStroke(path, stroke, thickness, lineJoin, dashArray, 0, aliased);
                    if (!fill.IsUndefined())
                    {
                        path.Fill = this.GetCachedBrush(fill);
                    }

                    if (usg)
                    {
                        streamGeometry = new StreamGeometry {
                            FillRule = FillRule.Nonzero
                        };
                        sgc = streamGeometry.Open();
                    }
                    else
                    {
                        pathGeometry = new PathGeometry {
                            FillRule = FillRule.Nonzero
                        };
                    }
                }

                PathFigure figure = null;
                bool       first  = true;
                foreach (var p in polygon)
                {
                    var point = aliased ? this.ToPixelAlignedPoint(p) : this.ToPoint(p);
                    if (first)
                    {
                        if (usg)
                        {
                            sgc.BeginFigure(point, !fill.IsUndefined(), true);
                        }
                        else
                        {
                            figure = new PathFigure
                            {
                                StartPoint = point,
                                IsFilled   = !fill.IsUndefined(),
                                IsClosed   = true
                            };
                            pathGeometry.Figures.Add(figure);
                        }

                        first = false;
                    }
                    else
                    {
                        if (usg)
                        {
                            sgc.LineTo(point, !stroke.IsUndefined(), true);
                        }
                        else
                        {
                            figure.Segments.Add(new LineSegment(point, !stroke.IsUndefined())
                            {
                                IsSmoothJoin = true
                            });
                        }
                    }
                }

                count++;

                // Must limit the number of figures, otherwise drawing errors...
                if (count > MaxFiguresPerGeometry)
                {
                    if (usg)
                    {
                        sgc.Close();
                        path.Data = streamGeometry;
                    }
                    else
                    {
                        path.Data = pathGeometry;
                    }

                    path  = null;
                    count = 0;
                }
            }

            if (path != null)
            {
                if (usg)
                {
                    sgc.Close();
                    path.Data = streamGeometry;
                }
                else
                {
                    path.Data = pathGeometry;
                }
            }
        }
コード例 #3
0
        void IBackgroundRenderer.Draw(TextView textView, DrawingContext drawingContext)
        {
            if (textView == null)
            {
                throw new ArgumentNullException(nameof(textView));
            }

            if (drawingContext == null)
            {
                throw new ArgumentNullException(nameof(drawingContext));
            }

            if (!textView.VisualLinesValid)
            {
                return;
            }

            var visualLines = textView.VisualLines;

            if (visualLines.Count == 0)
            {
                return;
            }

            int viewStart = visualLines.First().FirstDocumentLine.Offset;
            int viewEnd   = visualLines.Last().LastDocumentLine.EndOffset;

            foreach (TextMarker marker in _markers.FindOverlappingSegments(viewStart, viewEnd - viewStart))
            {
                var underlineMarkerTypes = TextMarkerTypes.SquigglyUnderline;
                if ((marker.MarkerTypes & underlineMarkerTypes) != 0)
                {
                    foreach (var r in BackgroundGeometryBuilder.GetRectsForSegment(textView, marker))
                    {
                        Point startPoint = r.BottomLeft;
                        Point endPoint   = r.BottomRight;

                        Brush usedBrush = new SolidColorBrush(marker.MarkerColor);
                        usedBrush.Freeze();
                        if ((marker.MarkerTypes & TextMarkerTypes.SquigglyUnderline) != 0)
                        {
                            double offset = 2.5;

                            int count = Math.Max((int)((endPoint.X - startPoint.X) / offset) + 1, 4);

                            StreamGeometry geometry = new StreamGeometry();

                            using (StreamGeometryContext ctx = geometry.Open())
                            {
                                ctx.BeginFigure(startPoint, false, false);
                                ctx.PolyLineTo(CreatePoints(startPoint, offset, count).ToArray(), true, false);
                            }

                            geometry.Freeze();

                            Pen usedPen = new Pen(usedBrush, 1);
                            usedPen.Freeze();
                            drawingContext.DrawGeometry(Brushes.Transparent, usedPen, geometry);
                        }
                    }
                }
            }
        }
コード例 #4
0
 /// <summary>
 /// Applies a new segment to the given one.
 /// </summary>
 /// <param name="pContext">The geometry context.</param>
 protected internal override void ApplyTo(StreamGeometryContext pContext)
 {
     pContext.QuadraticBezierTo(Point1, Point2);
 }
コード例 #5
0
        private static void DeserializeArcTo(BinaryReader br, byte firstByte, StreamGeometryContext sc)
        {
            Point point;
            Size size = new Size();
            double rotationAngle;
            bool isStroked;
            bool isSmoothJoin;
            bool isLargeArc;
            SweepDirection sweepDirection;

            DeserializePointAndTwoBools(br, firstByte, out point, out isStroked, out isSmoothJoin);

            // Read the packed byte for isLargeArd & sweepDirection.

            //
            // Pack isLargeArc & sweepDirection into a signle byte.
            //
            byte packedByte = br.ReadByte();

            isLargeArc = ((packedByte & LowNibble) != 0);

            sweepDirection = BoolToSweep(((packedByte & HighNibble) != 0));


            size.Width = XamlSerializationHelper.ReadDouble(br);
            size.Height = XamlSerializationHelper.ReadDouble(br);
            rotationAngle = XamlSerializationHelper.ReadDouble(br);

            sc.ArcTo(point, size, rotationAngle, isLargeArc, sweepDirection, isStroked, isSmoothJoin);
        }
コード例 #6
0
ファイル: LineSegment.cs プロジェクト: CarlSosaDev/Avalonia
 protected internal override void ApplyTo(StreamGeometryContext ctx)
 {
     ctx.LineTo(Point);
 }
コード例 #7
0
        private static void DeserializePolyQuadraticBezierTo(BinaryReader br, Byte firstByte, StreamGeometryContext sc)
        {
            bool          isStroked;
            bool          isSmoothJoin;
            IList <Point> points;

            points = DeserializeListOfPointsAndTwoBools(br, firstByte, out isStroked, out isSmoothJoin);

            sc.PolyQuadraticBezierTo(points, isStroked, isSmoothJoin);
        }
コード例 #8
0
        private static void DeserializeBeginFigure(BinaryReader br, Byte firstByte, StreamGeometryContext sc)
        {
            Point point;
            bool isFilled;
            bool isClosed;

            DeserializePointAndTwoBools(br, firstByte, out point, out isFilled, out isClosed);

            sc.BeginFigure(point, isFilled, isClosed);
        }
コード例 #9
0
ファイル: parserscommon.cs プロジェクト: dox0/DotNet471RS3
        /// <summary>
        /// Parse a PathFigureCollection string
        /// </summary>
        internal void ParseToGeometryContext(
            StreamGeometryContext context,
            string pathString,
            int startIndex)
        {
            // [BreakingChange] Dev10 Bug #453199
            // We really should throw an ArgumentNullException here for context and pathString.

            // From original code
            // This is only used in call to Double.Parse
            _formatProvider = System.Globalization.CultureInfo.InvariantCulture;

            _context    = context;
            _pathString = pathString;
            _pathLength = pathString.Length;
            _curIndex   = startIndex;

            _secondLastPoint = new Point(0, 0);
            _lastPoint       = new Point(0, 0);
            _lastStart       = new Point(0, 0);

            _figureStarted = false;

            bool first = true;

            char last_cmd = ' ';

            while (ReadToken()) // Empty path is allowed in XAML
            {
                char cmd = _token;

                if (first)
                {
                    if ((cmd != 'M') && (cmd != 'm'))  // Path starts with M|m
                    {
                        ThrowBadToken();
                    }

                    first = false;
                }

                switch (cmd)
                {
                case 'm':
                case 'M':
                    // XAML allows multiple points after M/m
                    _lastPoint = ReadPoint(cmd, !AllowComma);

                    context.BeginFigure(_lastPoint, IsFilled, !IsClosed);
                    _figureStarted = true;
                    _lastStart     = _lastPoint;
                    last_cmd       = 'M';

                    while (IsNumber(AllowComma))
                    {
                        _lastPoint = ReadPoint(cmd, !AllowComma);

                        context.LineTo(_lastPoint, IsStroked, !IsSmoothJoin);
                        last_cmd = 'L';
                    }
                    break;

                case 'l':
                case 'L':
                case 'h':
                case 'H':
                case 'v':
                case 'V':
                    EnsureFigure();

                    do
                    {
                        switch (cmd)
                        {
                        case 'l': _lastPoint = ReadPoint(cmd, !AllowComma); break;

                        case 'L': _lastPoint = ReadPoint(cmd, !AllowComma); break;

                        case 'h': _lastPoint.X += ReadNumber(!AllowComma); break;

                        case 'H': _lastPoint.X = ReadNumber(!AllowComma); break;

                        case 'v': _lastPoint.Y += ReadNumber(!AllowComma); break;

                        case 'V': _lastPoint.Y = ReadNumber(!AllowComma); break;
                        }

                        context.LineTo(_lastPoint, IsStroked, !IsSmoothJoin);
                    }while (IsNumber(AllowComma));

                    last_cmd = 'L';
                    break;

                case 'c':
                case 'C':           // cubic Bezier
                case 's':
                case 'S':           // smooth cublic Bezier
                    EnsureFigure();

                    do
                    {
                        Point p;

                        if ((cmd == 's') || (cmd == 'S'))
                        {
                            if (last_cmd == 'C')
                            {
                                p = Reflect();
                            }
                            else
                            {
                                p = _lastPoint;
                            }

                            _secondLastPoint = ReadPoint(cmd, !AllowComma);
                        }
                        else
                        {
                            p = ReadPoint(cmd, !AllowComma);

                            _secondLastPoint = ReadPoint(cmd, AllowComma);
                        }

                        _lastPoint = ReadPoint(cmd, AllowComma);

                        context.BezierTo(p, _secondLastPoint, _lastPoint, IsStroked, !IsSmoothJoin);

                        last_cmd = 'C';
                    }while (IsNumber(AllowComma));

                    break;

                case 'q':
                case 'Q':           // quadratic Bezier
                case 't':
                case 'T':           // smooth quadratic Bezier
                    EnsureFigure();

                    do
                    {
                        if ((cmd == 't') || (cmd == 'T'))
                        {
                            if (last_cmd == 'Q')
                            {
                                _secondLastPoint = Reflect();
                            }
                            else
                            {
                                _secondLastPoint = _lastPoint;
                            }

                            _lastPoint = ReadPoint(cmd, !AllowComma);
                        }
                        else
                        {
                            _secondLastPoint = ReadPoint(cmd, !AllowComma);
                            _lastPoint       = ReadPoint(cmd, AllowComma);
                        }

                        context.QuadraticBezierTo(_secondLastPoint, _lastPoint, IsStroked, !IsSmoothJoin);

                        last_cmd = 'Q';
                    }while (IsNumber(AllowComma));

                    break;

                case 'a':
                case 'A':
                    EnsureFigure();

                    do
                    {
                        // A 3,4 5, 0, 0, 6,7
                        double w        = ReadNumber(!AllowComma);
                        double h        = ReadNumber(AllowComma);
                        double rotation = ReadNumber(AllowComma);
                        bool   large    = ReadBool();
                        bool   sweep    = ReadBool();

                        _lastPoint = ReadPoint(cmd, AllowComma);

                        context.ArcTo(
                            _lastPoint,
                            new Size(w, h),
                            rotation,
                            large,
#if PBTCOMPILER
                            sweep,
#else
                            sweep ? SweepDirection.Clockwise : SweepDirection.Counterclockwise,
#endif
                            IsStroked,
                            !IsSmoothJoin
                            );
                    }while (IsNumber(AllowComma));

                    last_cmd = 'A';
                    break;

                case 'z':
                case 'Z':
                    EnsureFigure();
                    context.SetClosedState(IsClosed);

                    _figureStarted = false;
                    last_cmd       = 'Z';

                    _lastPoint = _lastStart; // Set reference point to be first point of current figure
                    break;

                default:
                    ThrowBadToken();
                    break;
                }
            }
        }
コード例 #10
0
        private static void DeserializeQuadraticBezierTo(BinaryReader br, byte firstByte, StreamGeometryContext sc)
        {
            Point point1;
            Point point2 = new Point();
            bool  isStroked;
            bool  isSmoothJoin;

            DeserializePointAndTwoBools(br, firstByte, out point1, out isStroked, out isSmoothJoin);

            point2.X = XamlSerializationHelper.ReadDouble(br);
            point2.Y = XamlSerializationHelper.ReadDouble(br);

            sc.QuadraticBezierTo(point1, point2, isStroked, isSmoothJoin);
        }
コード例 #11
0
ファイル: PathSegment.cs プロジェクト: CarlSosaDev/Avalonia
 protected internal abstract void ApplyTo(StreamGeometryContext ctx);
コード例 #12
0
 public StreamGeometryContext Open() {
   _Geo = new PathGeometry();
   StreamGeometryContext ctxt = new StreamGeometryContext(_Geo);
   return ctxt;
 }
コード例 #13
0
ファイル: ArcSegment.cs プロジェクト: CarlSosaDev/Avalonia
 protected internal override void ApplyTo(StreamGeometryContext ctx)
 {
     ctx.ArcTo(Point, Size, RotationAngle, IsLargeArc, SweepDirection);
 }
コード例 #14
0
        public void Draw(TextView textView, DrawingContext drawingContext)
        {
            if (textView == null)
            {
                throw new ArgumentNullException("textView");
            }
            if (drawingContext == null)
            {
                throw new ArgumentNullException("drawingContext");
            }
            if (markers == null || !textView.VisualLinesValid)
            {
                return;
            }
            var visualLines = textView.VisualLines;

            if (visualLines.Count == 0)
            {
                return;
            }
            int viewStart = visualLines.First().FirstDocumentLine.Offset;
            int viewEnd   = visualLines.Last().LastDocumentLine.EndOffset;

            foreach (TextMarker marker in markers.FindOverlappingSegments(viewStart, viewEnd - viewStart))
            {
                if (marker.BackgroundColor != null)
                {
                    BackgroundGeometryBuilder geoBuilder = new BackgroundGeometryBuilder();
                    geoBuilder.AlignToWholePixels = true;
                    geoBuilder.CornerRadius       = 3;
                    geoBuilder.AddSegment(textView, marker);
                    Geometry geometry = geoBuilder.CreateGeometry();
                    if (geometry != null)
                    {
                        Color           color = marker.BackgroundColor.Value;
                        SolidColorBrush brush = new SolidColorBrush(color);
                        brush.Freeze();
                        drawingContext.DrawGeometry(brush, null, geometry);
                    }
                }
                var underlineMarkerTypes = TextMarkerTypes.SquigglyUnderline | TextMarkerTypes.NormalUnderline | TextMarkerTypes.DottedUnderline;
                if ((marker.MarkerTypes & underlineMarkerTypes) != 0)
                {
                    foreach (Rect r in BackgroundGeometryBuilder.GetRectsForSegment(textView, marker))
                    {
                        Point startPoint = r.BottomLeft;
                        Point endPoint   = r.BottomRight;

                        Brush usedBrush = new SolidColorBrush(marker.MarkerColor);
                        usedBrush.Freeze();
                        if ((marker.MarkerTypes & TextMarkerTypes.SquigglyUnderline) != 0)
                        {
                            double offset = 2.5;

                            int count = Math.Max((int)((endPoint.X - startPoint.X) / offset) + 1, 4);

                            StreamGeometry geometry = new StreamGeometry();

                            using (StreamGeometryContext ctx = geometry.Open())
                            {
                                ctx.BeginFigure(startPoint, false, false);
                                ctx.PolyLineTo(CreatePoints(startPoint, endPoint, offset, count).ToArray(), true, false);
                            }

                            geometry.Freeze();

                            Pen usedPen = new Pen(usedBrush, 1);
                            usedPen.Freeze();
                            drawingContext.DrawGeometry(Brushes.Transparent, usedPen, geometry);
                        }
                        if ((marker.MarkerTypes & TextMarkerTypes.NormalUnderline) != 0)
                        {
                            Pen usedPen = new Pen(usedBrush, 1);
                            usedPen.Freeze();
                            drawingContext.DrawLine(usedPen, startPoint, endPoint);
                        }
                        if ((marker.MarkerTypes & TextMarkerTypes.DottedUnderline) != 0)
                        {
                            Pen usedPen = new Pen(usedBrush, 1);
                            usedPen.DashStyle = DashStyles.Dot;
                            usedPen.Freeze();
                            drawingContext.DrawLine(usedPen, startPoint, endPoint);
                        }
                    }
                }
            }
        }
コード例 #15
0
        private StreamGeometry CreateGeometry()
        {
            // Twice as much points for the calculation of intermediate point between cornerpoints

            int cornerPoints = CornerPoints * 2;

            // Incrementing angle based on amount of cornerpoints
            float incrementingAngle = 360f / cornerPoints;


            //Outer radius based on the minium widht or height of the shape

            float outerRadius = (float)Math.Min(RenderSize.Width / 2 - StrokeThickness / 2, RenderSize.Height / 2 - StrokeThickness / 2);


            //innerRadius calculation taking innerRadiusOffset as a percentage offset into account

            float innerRadiusOffset = (1 - InnerRadiusOffset / 100f);
            float innerRadius       = GetCos(incrementingAngle) * outerRadius * innerRadiusOffset;


            float rotationAnle = (float)RotationAngle;


            //Calculate and store points for geometry

            float x, y, angle;

            Point[] points = new Point[cornerPoints];

            for (int i = 0; i < cornerPoints; i++)
            {
                //Alternating point on outer and inner radius

                angle = i * incrementingAngle + rotationAnle;

                x = GetCos(angle) * outerRadius;
                y = GetSin(angle) * outerRadius;

                points[i] = new Point(x, y);

                Swap(ref outerRadius, ref innerRadius);
            }


            //Create the geometry

            StreamGeometry geometry = new StreamGeometry();

            using (StreamGeometryContext ctx = geometry.Open())
            {
                ctx.BeginFigure(points[0], true, true);

                for (int i = 1; i < cornerPoints; i++)
                {
                    ctx.LineTo(points[i], true, true);
                }
            }


            //Translate into shape center

            geometry.Transform = new TranslateTransform(outerRadius + StrokeThickness / 2, outerRadius + StrokeThickness / 2);

            return(geometry);
        }
コード例 #16
0
        public StreamGeometryPolyBezierToExample()
        {
            // Create a path to draw a geometry with.
            Path myPath = new Path();

            myPath.Stroke          = Brushes.Black;
            myPath.StrokeThickness = 1;

            // Create a StreamGeometry to use to specify myPath.
            StreamGeometry geometry = new StreamGeometry();

            geometry.FillRule = FillRule.EvenOdd;

            // Open a StreamGeometryContext that can be used to describe this StreamGeometry
            // object's contents.
            using (StreamGeometryContext ctx = geometry.Open())
            {
                // Set the begin point of the shape.
                ctx.BeginFigure(new Point(10, 100), true /* is filled */, false /* is closed */);

                // Create a collection of Point structures that will be used with the PolyBezierTo
                // Method to create the Bezier curve.
                List <Point> pointList = new List <Point>();

                // First Bezier curve is specified with these three points.

                // First control point for first Bezier curve.
                pointList.Add(new Point(100, 0));

                // Second control point for first Bezier curve.
                pointList.Add(new Point(200, 200));

                // Destination point for first Bezier curve.
                pointList.Add(new Point(300, 100));

                // Second Bezier curve is specified with these three points.

                // First control point for second Bezier curve.
                pointList.Add(new Point(400, 0));

                // Second control point for second Bezier curve.
                pointList.Add(new Point(500, 200));

                // Destination point for second Bezier curve.
                pointList.Add(new Point(600, 100));

                // Create a Bezier curve using the collection of Point Structures.
                ctx.PolyBezierTo(pointList, true /* is stroked */, false /* is smooth join */);
            }

            // Freeze the geometry (make it unmodifiable)
            // for additional performance benefits.
            geometry.Freeze();

            // specify the shape (Bezier curve) of the path using the StreamGeometry.
            myPath.Data = geometry;

            // Add path shape to the UI.
            StackPanel mainPanel = new StackPanel();

            mainPanel.Children.Add(myPath);
            this.Content = mainPanel;
        }
コード例 #17
0
ファイル: PieButton.cs プロジェクト: llorch19/H.Framework
        /// <summary>
        /// 绑定数据生成控件
        /// </summary>
        private void CreateControl()
        {
            if (ItemsSource == null || ItemsCount == 0)
            {
                return;
            }
            if (Width == double.NaN || Height == 0)
            {
                return;
            }
            if (mPanel == null)
            {
                return;
            }

            double          transformAngle  = -90 - 360 / ItemsCount / 2;
            RotateTransform rotateTransform = new RotateTransform(transformAngle)
            {
                CenterX = Width / 2, CenterY = Height / 2
            };

            //清空
            mPanel.Children.Clear();
            _ListPath.Clear();
            this.SelectedItem = null;

            var centerPoint = new Point(Width / 2, Height / 2);

            //Win32.POINT screenPos = new Win32.POINT();
            //var endPoint = PointFromScreen(new Point(screenPos.X, screenPos.Y));

            if (ItemsSource != null && !string.IsNullOrEmpty(DisplayPath))
            {
                int paletteIndex = 0;
                //Brush fill = new SolidColorBrush(Color.FromArgb(0xFF, 0xBA, 0xBA, 0xBA));
                //Brush stroke = new SolidColorBrush(Colors.Black);
                Style style = new Style();
                style.Setters.Add(new Setter {
                    Property = Path.FillProperty, Value = new SolidColorBrush(Color.FromArgb(0xFF, 0xBA, 0xBA, 0xBA))
                });
                style.Setters.Add(new Setter {
                    Property = Path.StrokeProperty, Value = new SolidColorBrush(Colors.Transparent)
                });
                int itemCount = 0;
                foreach (object item in ItemsSource)
                {
                    //获取调色板
                    if (Palette != null && Palette.Count > 0)
                    {
                        style = Palette[paletteIndex];
                        //foreach (Setter setter in style.Setters)
                        //{
                        //    if (setter.Property == Path.FillProperty)
                        //        fill = (Brush)setter.Value;
                        //    if (setter.Property == Path.StrokeProperty)
                        //        stroke = (Brush)setter.Value;
                        //}
                        paletteIndex++;
                        if (paletteIndex >= Palette.Count)
                        {
                            paletteIndex = 0;
                        }
                    }

                    PropertyInfo propertyDisplayText = item.GetType().GetProperty(DisplayPath);

                    //插入块
                    Path path = new Path();
                    path.Name            = "piePath";
                    path.Style           = style;
                    path.StrokeThickness = 0;
                    //pathFigure.Segments.Add(new ArcSegment
                    //{
                    //    Point = new Point(ActualWidth, ActualHeight / 2),
                    //    IsLargeArc = false,
                    //    Size = new Size(ActualWidth / ItemsCount * 3, ActualHeight / 2),
                    //    SweepDirection = SweepDirection.Clockwise
                    //});

                    //pathFigure.Segments.Add(new LineSegment
                    //{
                    //    Point = new Point(ActualWidth / ItemsCount * 3, ActualHeight / 2)
                    //});

                    //pathFigure.Segments.Add(new ArcSegment
                    //{
                    //    Point = new Point(ActualWidth / 2, ActualHeight / ItemsCount),
                    //    Size = new Size((ActualWidth / 2), 0),
                    //    SweepDirection = SweepDirection.Counterclockwise
                    //});
                    StreamGeometry  streamGeometry = new StreamGeometry();
                    int             previewPath    = 360 / ItemsCount * itemCount;
                    int             nextPath       = 360 / ItemsCount * (itemCount + 1);
                    PointCollection points         = new PointCollection();
                    using (StreamGeometryContext geometryContext = streamGeometry.Open())
                    {
                        for (int i = previewPath; i <= nextPath; i++)
                        {
                            double pathOutterAngle = Math.PI * (i / 180.0);
                            double outterY         = Height / 2 + (OutterCircleSize * Math.Sin(pathOutterAngle));
                            double outterX         = Width / 2 + (OutterCircleSize * Math.Cos(pathOutterAngle));
                            Point  OutterPoint     = new Point(outterX, outterY);
                            if (i == previewPath)
                            {
                                geometryContext.BeginFigure(OutterPoint, true, true);
                            }
                            else
                            {
                                points.Add(OutterPoint);
                            }
                        }

                        for (int j = nextPath - 1; j >= previewPath; j--)
                        {
                            double pathInnerAngle = Math.PI * (j / 180.0);
                            double innerY         = Height / 2 + (InnerCircleSize * Math.Sin(pathInnerAngle));
                            double innerX         = Width / 2 + (InnerCircleSize * Math.Cos(pathInnerAngle));
                            Point  innerPoint     = new Point(innerX, innerY);
                            points.Add(innerPoint);
                        }
                        geometryContext.PolyLineTo(points, true, true);
                    }
                    _ListPoints.Add(points);
                    itemCount++;
                    path.Opacity = 0;
                    path.Data    = streamGeometry;
                    path.Tag     = item;
                    TransformGroup group = new TransformGroup();
                    group.Children.Add(rotateTransform);
                    path.RenderTransform = group;
                    DoubleAnimation opacityUpAnmiation = new DoubleAnimation();
                    opacityUpAnmiation.BeginTime = new TimeSpan(0, 0, 0, 0, itemCount * 90 - 20);
                    opacityUpAnmiation.Duration  = new Duration(TimeSpan.FromSeconds(0.2));
                    opacityUpAnmiation.From      = 0;
                    opacityUpAnmiation.To        = 0.95;

                    Storyboard.SetTarget(opacityUpAnmiation, path);
                    Storyboard.SetTargetProperty(opacityUpAnmiation, new PropertyPath("Opacity"));
                    _ShowUpStoryboard.Children.Add(opacityUpAnmiation);

                    DoubleAnimation opacityDownAnmiation = new DoubleAnimation();
                    opacityDownAnmiation.BeginTime = new TimeSpan(0, 0, 0, 0, itemCount * 90 - 20);
                    opacityDownAnmiation.Duration  = new Duration(TimeSpan.FromSeconds(0.2));
                    opacityDownAnmiation.From      = 0.95;
                    opacityDownAnmiation.To        = 0;

                    Storyboard.SetTarget(opacityDownAnmiation, path);
                    Storyboard.SetTargetProperty(opacityDownAnmiation, new PropertyPath("Opacity"));
                    _HiddenStoryboard.Children.Add(opacityDownAnmiation);

                    //path.Visibility = Visibility.Collapsed;

                    //ObjectAnimationUsingKeyFrames visibilityAnimation = new ObjectAnimationUsingKeyFrames();
                    //DiscreteObjectKeyFrame frame = new DiscreteObjectKeyFrame(Visibility.Visible, new TimeSpan(0, 0, 0, 5));
                    //visibilityAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.5));
                    //visibilityAnimation.KeyFrames.Add(frame);
                    //visibilityAnimation.BeginTime = new TimeSpan(0, 0, 0, 0, itemCount * 90 - 20);
                    //Storyboard.SetTarget(visibilityAnimation, path);
                    //Storyboard.SetTargetProperty(visibilityAnimation, new PropertyPath("Visibility"));
                    //_ShowUpStoryboard.Children.Add(visibilityAnimation);
                    //DoubleAnimationUsingPath pathAnmiation = new DoubleAnimationUsingPath();
                    //pathAnmiation.BeginTime = new TimeSpan(0, 0, 0, 0, paletteIndex * 150);
                    //pathAnmiation.Duration = new Duration(TimeSpan.FromSeconds(0.5));
                    //pathAnmiation.PathGeometry = path.Data.GetFlattenedPathGeometry();

                    //Storyboard.SetTarget(pathAnmiation, path);
                    //Storyboard.SetTargetProperty(pathAnmiation, new PropertyPath("Data.Figures[0].Segments[0].Point"));

                    //sboard.Children.Add(pathAnmiation);
                    //path.MouseEnter += (sender, e) =>
                    //{
                    //    AnimationHelper.ScaleEasingInAnimation(path, isActivatedScaleAnimation);
                    //};

                    //path.MouseLeave += (sender, e) =>
                    //{
                    //    AnimationHelper.ScaleEasingOutAnimation(path);
                    //    isActivatedScaleAnimation = true;
                    //};

                    //path.MouseUp += (sender, e) =>
                    //{
                    //    path_MouseUp(path);
                    //};
                    Panel.SetZIndex(path, 3);
                    mPanel.Children.Add(path);
                    _ListPath.Add(path);

                    //插入文字
                    if (ShowText)
                    {
                        double mAngle       = 1 * 360 / ItemsCount + 0;
                        string title        = propertyDisplayText.GetValue(item, null).ToString();
                        double cAngle       = ((nextPath + previewPath) / 2.0 + transformAngle) % 360;
                        double titleAngle   = Math.PI * (cAngle / 180.0);
                        double titleOutterY = Height / 2 + (OutterCircleSize * Math.Sin(titleAngle));
                        double titleOutterX = Width / 2 + (OutterCircleSize * Math.Cos(titleAngle));
                        double titleInnerY  = Height / 2 + (InnerCircleSize * Math.Sin(titleAngle));
                        double titleInnerX  = Width / 2 + (InnerCircleSize * Math.Cos(titleAngle));
                        double length       = Math.Sqrt(Math.Pow(titleOutterX - titleInnerX, 2) + Math.Pow(titleOutterY - titleInnerY, 2));
                        Size   titleSize    = ComputeRect(title, ShowTextSize);
                        double halfHeight   = titleSize.Height / 2;
                        double pers         = halfHeight / length + 0.5;
                        Point  titlePoint   = new Point(titleInnerX + (titleOutterX - titleInnerX) * pers, titleInnerY + (titleOutterY - titleInnerY) * pers);

                        TextBlock textBlock = new TextBlock {
                            Name = "pieBlock", TextWrapping = TextWrapping.NoWrap, TextAlignment = TextAlignment.Center, Text = title, FontSize = ShowTextSize, FontWeight = FontWeights.Bold, Foreground = new SolidColorBrush(Colors.White), Style = null, Opacity = 0
                        };
                        textBlock.HorizontalAlignment = HorizontalAlignment.Left;
                        textBlock.VerticalAlignment   = VerticalAlignment.Top;
                        textBlock.Margin = new Thickness(title.Length < 4 ? titlePoint.X + LabelSpace - 12 : titlePoint.X + LabelSpace - 20, titlePoint.Y + LabelSpace - 8, 0, 0);
                        //if (mAngle <= 90)
                        //{
                        //    //textBlock.HorizontalAlignment = HorizontalAlignment.Left;
                        //    //textBlock.VerticalAlignment = VerticalAlignment.Bottom;
                        //    textBlock.Margin = new Thickness(titlePoint.X + LabelSpace - 12, 0, 0, this.ActualHeight - titlePoint.Y + LabelSpace - 6);
                        //}
                        //else
                        //{
                        //    if (mAngle <= 180)
                        //    {
                        //        //textBlock.HorizontalAlignment = HorizontalAlignment.Left;
                        //        //textBlock.VerticalAlignment = VerticalAlignment.Top;
                        //        textBlock.Margin = new Thickness(titlePoint.X + LabelSpace - 12, titlePoint.Y + LabelSpace - 6, 0, 0);
                        //    }
                        //    else
                        //    {
                        //        if (mAngle <= 270)
                        //        {
                        //            //textBlock.HorizontalAlignment = HorizontalAlignment.Right;
                        //            //textBlock.VerticalAlignment = VerticalAlignment.Top;
                        //            textBlock.Margin = new Thickness(0, titlePoint.Y + LabelSpace - 6, this.ActualWidth - titlePoint.X + LabelSpace + 12, 0);
                        //        }
                        //        else
                        //        {
                        //            //textBlock.HorizontalAlignment = HorizontalAlignment.Right;
                        //            //textBlock.VerticalAlignment = VerticalAlignment.Bottom;
                        //            textBlock.Margin = new Thickness(0, 0, this.ActualWidth + LabelSpace - 12, this.ActualHeight + LabelSpace - 12);
                        //        }
                        //    }
                        //}

                        //textBlock.MouseEnter += (sender, e) =>
                        //{
                        //    AnimationHelper.ScaleEasingInAnimation(path, false);
                        //};

                        //textBlock.MouseLeave += (sender, e) =>
                        //{
                        //    AnimationHelper.ScaleEasingInAnimation(path, false);
                        //    isActivatedScaleAnimation = false;
                        //};

                        //textBlock.MouseUp += (sender, e) =>
                        //{
                        //    path_MouseUp(path);
                        //};

                        DoubleAnimation opacityTextUpAnmiation = new DoubleAnimation();
                        opacityTextUpAnmiation.BeginTime = new TimeSpan(0, 0, 0, 0, itemCount * 90 - 20);
                        opacityTextUpAnmiation.Duration  = new Duration(TimeSpan.FromSeconds(0.2));
                        opacityTextUpAnmiation.From      = 0;
                        opacityTextUpAnmiation.To        = 0.95;
                        Storyboard.SetTarget(opacityTextUpAnmiation, textBlock);
                        Storyboard.SetTargetProperty(opacityTextUpAnmiation, new PropertyPath("Opacity"));
                        _ShowUpStoryboard.Children.Add(opacityTextUpAnmiation);

                        DoubleAnimation opacityTextDownAnmiation = new DoubleAnimation();
                        opacityTextDownAnmiation.BeginTime = new TimeSpan(0, 0, 0, 0, itemCount * 90 - 20);
                        opacityTextDownAnmiation.Duration  = new Duration(TimeSpan.FromSeconds(0.2));
                        opacityTextDownAnmiation.From      = 0.95;
                        opacityTextDownAnmiation.To        = 0;

                        Storyboard.SetTarget(opacityTextDownAnmiation, textBlock);
                        Storyboard.SetTargetProperty(opacityTextDownAnmiation, new PropertyPath("Opacity"));
                        _HiddenStoryboard.Children.Add(opacityTextDownAnmiation);
                        Panel.SetZIndex(textBlock, 6);
                        mPanel.Children.Add(textBlock);
                    }
                }
            }
        }
コード例 #18
0
        private static void DeserializeBezierTo(BinaryReader br, byte firstByte, StreamGeometryContext sc)
        {
            Point point1;
            Point point2 = new Point();
            Point point3 = new Point();

            bool isStroked;
            bool isSmoothJoin;

            DeserializePointAndTwoBools(br, firstByte, out point1, out isStroked, out isSmoothJoin);

            point2.X = XamlSerializationHelper.ReadDouble(br);
            point2.Y = XamlSerializationHelper.ReadDouble(br);

            point3.X = XamlSerializationHelper.ReadDouble(br);
            point3.Y = XamlSerializationHelper.ReadDouble(br);

            sc.BezierTo(point1, point2, point3, isStroked, isSmoothJoin);
        }
コード例 #19
0
ファイル: Edge.cs プロジェクト: SweaterPower/GraphWork
        private void InternalDrawArrowGeometry(StreamGeometryContext context)
        {
            //double k = (-1 * (Y1 - Y2)) / (X2 - X1);
            //double a = Math.Atan(k);
            //if (X1 > X2)
            //{
            //    a = Math.PI - a;
            //    a *= -1;
            //}

            //Point pt1 = new Point(X1, this.Y1);
            //Point pt2 = new Point(X2, this.Y2);

            //double height = Math.Sqrt((pt2.X - pt1.X) * (pt2.X - pt1.X) + (pt2.Y - pt1.Y) * (pt2.Y - pt1.Y));
            //double width = Math.Abs(Curveture) * 2.5 + height / 10;

            //double Ax = (X1 + X2) / 2;
            //double Ay = (Y1 + Y2) / 2;
            //double b = Math.Atan(-1 / (-1 * (Y1 - Y2) / (X2 - X1)));
            //if (Y1 >= Ay)
            //{
            //    b = Math.PI - b;
            //    b *= -1;
            //}
            //double modifier = Curveture * 0.2;
            //double Bx = X1 + modifier * Math.Cos(b);
            //double By = Y1 + modifier * Math.Sin(b);
            //TopX = Ax + modifier * Math.Cos(b);
            //TopY = Ay + modifier * Math.Sin(b);

            ////double length = Math.Sqrt((Bx - X2) * (Bx - X2) + (By - Y2) * (By - Y2));
            //Point ptGap = new Point(X2 - (Gap + 3) * Math.Cos(a), Y2 - (Gap + 3) * Math.Sin(a));
            //ptGap = new Point(ptGap.X + modifier * Math.Cos(b), ptGap.Y + modifier * Math.Sin(b));

            //Point ptEnd = new Point(X2 - (Gap + 23) * Math.Cos(a), Y2 - (Gap + 23) * Math.Sin(a));
            //ptEnd = new Point(ptGap.X + modifier * Math.Cos(b), ptGap.Y + modifier * Math.Sin(b));

            //double theta = Math.Atan2(By - ptGap.Y, Bx - ptGap.X);
            //double sint = Math.Sin(theta);
            //double cost = Math.Cos(theta);

            //Point pt3 = new Point(
            //    ptGap.X + (HeadWidth * cost - HeadHeight * sint),
            //    ptGap.Y + (HeadWidth * sint + HeadHeight * cost));

            //Point pt4 = new Point(
            //    ptGap.X + (HeadWidth * cost + HeadHeight * sint),
            //    ptGap.Y - (HeadHeight * cost - HeadWidth * sint));

            //context.BeginFigure(pt1, true, false);
            //context.LineTo(new Point(Bx, By), true, true);
            //////context.LineTo(ptGap, true, true);
            ////context.LineTo(new Point(Bx, By), true, true);
            ////context.LineTo(new Point(Ax, Ay), true, true);
            ////context.LineTo(pt1, true, true);
            ////context.ArcTo(ptEnd, new Size(height, width), a / Math.PI * 180, false, Curveture > 0 ? SweepDirection.Clockwise : SweepDirection.Counterclockwise, true, true);
            //context.LineTo(ptGap, true, true);
            //if (HasArrow)
            //{
            //    context.LineTo(pt3, true, true);
            //    context.LineTo(ptGap, true, true);
            //    context.LineTo(pt4, true, true);
            //    context.LineTo(ptGap, true, true);
            //}
            //context.LineTo(pt2, true, true);

            /*Point pt1 = new Point(X1, this.Y1);
             * Point pt2 = new Point(X2, this.Y2);
             *
             * double k = (-1 * (Y1 - Y2)) / (X2 - X1);
             * double a = Math.Atan(k);
             * if (X1 > X2)
             * {
             *  a = Math.PI - a;
             *  a *= -1;
             * }
             *
             * double Ax = (X1 + X2) / 2;
             * double Ay = (Y1 + Y2) / 2;
             * double b = Math.Atan(-1 / (-1 * (Y1 - Y2) / (X2 - X1)));
             * if (Y1 >= Ay)
             * {
             *  b = Math.PI - b;
             *  b *= -1;
             * }
             *
             * double modifier = Curveture * 0.2;
             * double Bx = X1 + modifier * Math.Cos(b);
             * double By = Y1 + modifier * Math.Sin(b);
             *
             * double gapx = X2 - (Gap + 3) * Math.Cos(a);
             * double gapy = Y2 - (Gap + 3) * Math.Sin(a);
             * Point ptGap = new Point(gapx + modifier * Math.Cos(b), gapy + modifier * Math.Sin(b));
             *
             * k = (-1 * (Y2 - ptGap.Y)) / (X2 - ptGap.X);
             * double theta = Math.Atan(k);
             * double sint = Math.Sin(theta);
             * double cost = Math.Cos(theta);
             *
             * double height = Math.Sqrt((pt2.X - pt1.X) * (pt2.X - pt1.X) + (pt2.Y - pt1.Y) * (pt2.Y - pt1.Y));
             * double width = Math.Abs(Curveture) * 2.5 + height / 10;
             *
             * Point pt3 = new Point(
             *  ptGap.X + (HeadWidth * cost - HeadHeight * sint),
             *  ptGap.Y + (HeadWidth * sint + HeadHeight * cost));
             *
             * Point pt4 = new Point(
             *  ptGap.X + (HeadWidth * cost + HeadHeight * sint),
             *  ptGap.Y - (HeadHeight * cost - HeadWidth * sint));
             *
             * TopX = Ax + modifier * Math.Cos(b);
             * TopY = Ay + modifier * Math.Sin(b);
             * context.BeginFigure(pt1, true, false);
             * context.ArcTo(ptGap, new Size(height, width), a / Math.PI * 180, false, Curveture > 0 ? SweepDirection.Clockwise : SweepDirection.Counterclockwise, true, true);
             * //context.LineTo(ptGap, true, true);
             * if (HasArrow)
             * {
             *  context.LineTo(pt3, true, true);
             *  context.LineTo(ptGap, true, true);
             *  context.LineTo(pt4, true, true);
             *  context.LineTo(ptGap, true, true);
             * }
             * context.LineTo(pt2, true, true);*/
            double k     = (Y2 - Y1) / (X2 - X1);
            double theta = Math.Atan(k);

            if (X1 > X2)
            {
                theta  = Math.PI - theta;
                theta *= -1;
            }
            double b = Math.Atan(-1 / k);
            //if (Y1 >= Y2)
            //{
            //    b = Math.PI - b;
            //    b *= -1;
            //}

            double sint = Math.Sin(theta);
            double cost = Math.Cos(theta);
            double sina = Math.Sin(b);
            double cosa = Math.Cos(b);

            //Math.Sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1)) / 2;
            double modifier = Curveture * -0.2;
            double Ax       = X1 + modifier * cosa;
            double Ay       = Y1 + modifier * sina;
            double Bx       = X2 + modifier * cosa;
            double By       = Y2 + modifier * sina;

            TopX = (X1 + X2) / 2;
            TopY = (Y1 + Y2) / 2;

            Point pt0 = new Point(X1, Y1);
            Point pt5 = new Point(X2, Y2);
            Point pt1 = new Point(Ax, Ay);
            Point pt2 = new Point(Bx, By);

            double gapx  = Bx - (Gap + 3) * cost;
            double gapy  = By - (Gap + 3) * sint;
            Point  ptGap = new Point(gapx, gapy);

            Point pt3 = new Point(
                ptGap.X - (HeadWidth * cost - HeadHeight * sint),
                ptGap.Y - (HeadWidth * sint + HeadHeight * cost));

            Point pt4 = new Point(
                ptGap.X - (HeadWidth * cost + HeadHeight * sint),
                ptGap.Y + (HeadHeight * cost - HeadWidth * sint));

            context.BeginFigure(pt0, true, false);
            context.LineTo(pt1, true, true);
            context.LineTo(ptGap, true, true);
            if (HasArrow)
            {
                context.LineTo(pt3, true, true);
                context.LineTo(ptGap, true, true);
                context.LineTo(pt4, true, true);
                context.LineTo(ptGap, true, true);
            }
            context.LineTo(pt2, true, true);
            context.LineTo(pt5, true, true);
        }
コード例 #20
0
 public StreamGeometryContext Open() {
   _Geo = new PathGeometry();
   _Geo.Figures = new PathFigureCollection();  // necessary for Geo.PathGeometryHasFigures to work
   StreamGeometryContext ctxt = new StreamGeometryContext(_Geo);
   return ctxt;
 }
コード例 #21
0
        public void Draw(TextView textView, DrawingContext drawingContext)
        {
            // validate parameters
            if (textView == null)
            {
                throw new ArgumentNullException(nameof(textView));
            }
            if (drawingContext == null)
            {
                throw new ArgumentNullException(nameof(drawingContext));
            }

            if (markers != null && textView.VisualLinesValid)
            {
                var visualLines = textView.VisualLines;
                if (visualLines.Count == 0)
                {
                    return;
                }
                int viewStart = visualLines.First().FirstDocumentLine.Offset;
                int viewEnd   = visualLines.Last().LastDocumentLine.EndOffset;
                foreach (TextMarker marker in markers.FindOverlappingSegments(viewStart, viewEnd - viewStart))
                {
                    if (marker.BackgroundColor != null)
                    {
                        var geoBuilder = new BackgroundGeometryBuilder {
                            AlignToWholePixels = true, CornerRadius = 3
                        };
                        geoBuilder.AddSegment(textView, marker);
                        Geometry geometry = geoBuilder.CreateGeometry();
                        if (geometry != null)
                        {
                            Color color = marker.BackgroundColor.Value;
                            var   brush = new SolidColorBrush(color);
                            brush.Freeze();
                            drawingContext.DrawGeometry(brush, null, geometry);
                        }
                    }
                    foreach (Rect r in BackgroundGeometryBuilder.GetRectsForSegment(textView, marker))
                    {
                        Point startPoint = r.BottomLeft;
                        Point endPoint   = r.BottomRight;

                        double yOffset = 1;
                        startPoint.Offset(0, yOffset);
                        endPoint.Offset(0, yOffset);

                        var usedPen = new Pen(new SolidColorBrush(marker.MarkerColor), 1);
                        usedPen.Freeze();
                        const double offset = 2.5;

                        int count = Math.Max((int)((endPoint.X - startPoint.X) / offset) + 1, 4);

                        var geometry = new StreamGeometry();

                        using (StreamGeometryContext ctx = geometry.Open())
                        {
                            ctx.BeginFigure(startPoint, false, false);
                            ctx.PolyLineTo(CreatePoints(startPoint, offset, count).ToArray(), true, false);
                        }

                        geometry.Freeze();

                        drawingContext.DrawGeometry(Brushes.Transparent, usedPen, geometry);
                        break;
                    }
                }
            }
        }
コード例 #22
0
ファイル: CogwheelShape.cs プロジェクト: kronic/Yatse2
        private StreamGeometry CreateGeometry()
        {
            // Twice as much corner points for every Tooth

            int cornerPoints = Teeth * 2;

            // Incrementing angle based on amount of cornerPoints

            float incrementingAngle = 360f / cornerPoints;


            //Outer radius based on the minium width or height of the shape

            float outerRadius =
                (float)
                Math.Min(RenderSize.Width / 2 - StrokeThickness / 2, RenderSize.Height / 2 - StrokeThickness / 2);


            //middleRadius calculation taking MiddleRadiusOffset as a percentage offset from outerRadius into account

            float middleRadiusOffset = (1 - MiddleRadiusOffset / 100f);
            float middleRadius       = outerRadius * middleRadiusOffset;

            //innerRadius calculation taking InnerRadiusOffset as a percentage offset from middleRadius into account

            float innerRadiusOffset = (1 - InnerRadiusOffset / 100f);
            float innerRadius       = middleRadius * innerRadiusOffset;

            //Bevel Angle calculation as  percentage amount of the half the incrementingAngle;

            float bevel      = (1 - Bevel / 100f);
            float bevelAngle = incrementingAngle / 2 * bevel;


            //rotationAngle for possible rotation adjustments for convencience of shape use

            float rotationAngle = (float)RotationAngle;


            //Array of three times as much cornerpoints to store intermediate points on each radius for the given incrementingAngle

            Point[] points = new Point[cornerPoints * 3];


            //Calculate and store points for geometry


            float anglePointX, anglePointY;
            float angleBevelPointX, angleBevelPointY;
            float angle;
            float x, y;

            for (int i = 0; i < cornerPoints; i++)
            {
                angle = i * incrementingAngle + rotationAngle;

                anglePointX = GetCos(angle);
                anglePointY = GetSin(angle);

                angleBevelPointX = GetCos(angle - bevelAngle);
                angleBevelPointY = GetSin(angle - bevelAngle);


                //For every iteration step calculate one point on each radius for the given angle


                //BevelPoint on outer radius

                x = angleBevelPointX * outerRadius;
                y = angleBevelPointY * outerRadius;

                points[i * 3] = new Point(x, y);

                //point on middle radius

                x = anglePointX * middleRadius;
                y = anglePointY * middleRadius;

                points[i * 3 + 1] = new Point(x, y);

                //point on inner radius

                x = anglePointX * innerRadius;
                y = anglePointY * innerRadius;

                points[i * 3 + 2] = new Point(x, y);


                //every second iteration swap stored points on inner and outer radius to reflect
                //the direction of points for ease of later geometry creation

                if (i % 2 != 0)
                {
                    Swap(ref points[i * 3], ref points[i * 3 + 2]);
                }

                //Alternate positive and negative bevelAngle;
                bevelAngle *= -1;
            }


            //Create the geometry

            StreamGeometry geometry = new StreamGeometry();

            using (StreamGeometryContext ctx = geometry.Open())
            {
                ctx.BeginFigure(points[0], true, true);

                for (int i = 1; i < points.Length; i++)
                {
                    ctx.LineTo(points[i], true, true);

                    //ctx.ArcTo(points[i],new Size(outerRadius,outerRadius),0,false,SweepDirection.Clockwise,true,true);
                }
            }

            //Translate into shape center

            geometry.Transform = new TranslateTransform(outerRadius + StrokeThickness / 2,
                                                        outerRadius + StrokeThickness / 2);


            return(geometry);
        }
コード例 #23
0
ファイル: RegionMarker.cs プロジェクト: FieldDB/cog
        public override void RegenerateShape(GMapControl map)
        {
            if (map != null)
            {
                if (Points.Count > 1)
                {
                    var localPath = new List <Point>();
                    var offset    = map.FromLatLngToLocal(Points[0]);
                    foreach (PointLatLng i in Points)
                    {
                        var p = map.FromLatLngToLocal(new PointLatLng(i.Lat, i.Lng));
                        localPath.Add(new Point(p.X - offset.X, p.Y - offset.Y));
                    }

                    // Create a StreamGeometry to use to specify myPath.
                    var geometry = new StreamGeometry();

                    using (StreamGeometryContext ctx = geometry.Open())
                    {
                        ctx.BeginFigure(localPath[0], true, true);

                        // Draw a line to the next specified point.
                        ctx.PolyLineTo(localPath, true, true);
                    }

                    // Freeze the geometry (make it unmodifiable)
                    // for additional performance benefits.
                    geometry.Freeze();

                    var fillBrush = new SolidColorBrush();
                    BindingOperations.SetBinding(fillBrush, SolidColorBrush.ColorProperty, new Binding("Variety.ClusterIndex")
                    {
                        Converter = new IndexToColorConverter(), ConverterParameter = Colors.CornflowerBlue
                    });
                    var strokeBrush = new SolidColorBrush();
                    BindingOperations.SetBinding(strokeBrush, SolidColorBrush.ColorProperty, new Binding("Color")
                    {
                        Source = fillBrush, Converter = new ColorBrightnessConverter(), ConverterParameter = -0.15
                    });
                    // Create a path to draw a geometry with.
                    var path = new Path
                    {
                        Data   = geometry,
                        Effect = new BlurEffect {
                            KernelType = KernelType.Gaussian, Radius = 3.0, RenderingBias = RenderingBias.Quality
                        },
                        Stroke           = strokeBrush,
                        Fill             = fillBrush,
                        StrokeThickness  = 3,
                        Opacity          = 0.5,
                        IsHitTestVisible = true,
                        DataContext      = _region,
                        Visibility       = Shape == null ? Visibility.Visible : Shape.Visibility
                    };
                    Shape             = path;
                    Shape.MouseEnter += Shape_MouseEnter;
                    Shape.MouseLeave += Region_MouseLeave;
                }
                else
                {
                    Shape = null;
                }
            }
        }
コード例 #24
0
ファイル: GeometryHelper.cs プロジェクト: robness/Vixen
        /// <summary>
        /// Gets the RoundRectangle Geometry for a rectangle having a
        /// given thickness and corner radius.
        /// </summary>
        /// <param name="baseRect">Base Rectangle</param>
        /// <param name="thickness">Border thickness</param>
        /// <param name="cornerRadius">CornerRadius</param>
        /// <returns>Geometry</returns>
        public static Geometry GetRoundRectangle(Rect baseRect, Thickness thickness, CornerRadius cornerRadius)
        {
            // Normalizing the corner radius
            if (cornerRadius.TopLeft < Double.Epsilon)
            {
                cornerRadius.TopLeft = 0.0;
            }
            if (cornerRadius.TopRight < Double.Epsilon)
            {
                cornerRadius.TopRight = 0.0;
            }
            if (cornerRadius.BottomLeft < Double.Epsilon)
            {
                cornerRadius.BottomLeft = 0.0;
            }
            if (cornerRadius.BottomRight < Double.Epsilon)
            {
                cornerRadius.BottomRight = 0.0;
            }

            // Taking the border thickness into account
            double leftHalf = thickness.Left * 0.5;

            if (leftHalf < Double.Epsilon)
            {
                leftHalf = 0.0;
            }
            double topHalf = thickness.Top * 0.5;

            if (topHalf < Double.Epsilon)
            {
                topHalf = 0.0;
            }
            double rightHalf = thickness.Right * 0.5;

            if (rightHalf < Double.Epsilon)
            {
                rightHalf = 0.0;
            }
            double bottomHalf = thickness.Bottom * 0.5;

            if (bottomHalf < Double.Epsilon)
            {
                bottomHalf = 0.0;
            }

            //baseRect = new Rect(baseRect.Location.X, baseRect.Location.Y, baseRect.Width + leftHalf + rightHalf, baseRect.Height + topHalf + bottomHalf);

            double tolerance = baseRect.Height < baseRect.Width ? baseRect.Height / baseRect.Width : baseRect.Width / baseRect.Height;

            // Create the rectangles for the corners that needs to be curved in the base rectangle
            // TopLeft Rectangle
            Rect topLeftRect = new Rect(baseRect.Location.X - tolerance,
                                        baseRect.Location.Y - tolerance,
                                        Math.Max(0.0, cornerRadius.TopLeft - leftHalf),
                                        Math.Max(0.0, cornerRadius.TopLeft - topHalf));
            // TopRight Rectangle
            Rect topRightRect = new Rect(baseRect.Location.X + baseRect.Width - cornerRadius.TopRight + rightHalf + tolerance,
                                         baseRect.Location.Y - tolerance,
                                         Math.Max(0.0, cornerRadius.TopRight - rightHalf),
                                         Math.Max(0.0, cornerRadius.TopRight - topHalf));
            // BottomRight Rectangle
            Rect bottomRightRect = new Rect(baseRect.Location.X + baseRect.Width - cornerRadius.BottomRight + rightHalf + tolerance,
                                            baseRect.Location.Y + baseRect.Height - cornerRadius.BottomRight + bottomHalf + tolerance,
                                            Math.Max(0.0, cornerRadius.BottomRight - rightHalf),
                                            Math.Max(0.0, cornerRadius.BottomRight - bottomHalf));
            // BottomLeft Rectangle
            Rect bottomLeftRect = new Rect(baseRect.Location.X - tolerance,
                                           baseRect.Location.Y + baseRect.Height - cornerRadius.BottomLeft + bottomHalf + tolerance,
                                           Math.Max(0.0, cornerRadius.BottomLeft - leftHalf),
                                           Math.Max(0.0, cornerRadius.BottomLeft - bottomHalf));

            // Adjust the width of the TopLeft and TopRight rectangles so that they are proportional to the width of the baseRect
            if (topLeftRect.Right > topRightRect.Left)
            {
                double newWidth = (topLeftRect.Width / (topLeftRect.Width + topRightRect.Width)) * baseRect.Width;
                topLeftRect  = new Rect(topLeftRect.Location.X, topLeftRect.Location.Y, newWidth, topLeftRect.Height);
                topRightRect = new Rect(baseRect.Left + newWidth, topRightRect.Location.Y, Math.Max(0.0, baseRect.Width - newWidth), topRightRect.Height);
            }

            // Adjust the height of the TopRight and BottomRight rectangles so that they are proportional to the height of the baseRect
            if (topRightRect.Bottom > bottomRightRect.Top)
            {
                double newHeight = (topRightRect.Height / (topRightRect.Height + bottomRightRect.Height)) * baseRect.Height;
                topRightRect    = new Rect(topRightRect.Location.X, topRightRect.Location.Y, topRightRect.Width, newHeight);
                bottomRightRect = new Rect(bottomRightRect.Location.X, baseRect.Top + newHeight, bottomRightRect.Width, Math.Max(0.0, baseRect.Height - newHeight));
            }

            // Adjust the width of the BottomLeft and BottomRight rectangles so that they are proportional to the width of the baseRect
            if (bottomRightRect.Left < bottomLeftRect.Right)
            {
                double newWidth = (bottomLeftRect.Width / (bottomLeftRect.Width + bottomRightRect.Width)) * baseRect.Width;
                bottomLeftRect  = new Rect(bottomLeftRect.Location.X, bottomLeftRect.Location.Y, newWidth, bottomLeftRect.Height);
                bottomRightRect = new Rect(baseRect.Left + newWidth, bottomRightRect.Location.Y, Math.Max(0.0, baseRect.Width - newWidth), bottomRightRect.Height);
            }

            // Adjust the height of the TopLeft and BottomLeft rectangles so that they are proportional to the height of the baseRect
            if (bottomLeftRect.Top < topLeftRect.Bottom)
            {
                double newHeight = (topLeftRect.Height / (topLeftRect.Height + bottomLeftRect.Height)) * baseRect.Height;
                topLeftRect    = new Rect(topLeftRect.Location.X, topLeftRect.Location.Y, topLeftRect.Width, newHeight);
                bottomLeftRect = new Rect(bottomLeftRect.Location.X, baseRect.Top + newHeight, bottomLeftRect.Width, Math.Max(0.0, baseRect.Height - newHeight));
            }

            StreamGeometry roundedRectGeometry = new StreamGeometry();

            using (StreamGeometryContext context = roundedRectGeometry.Open())
            {
                // Begin from the Bottom of the TopLeft Arc and proceed clockwise
                context.BeginFigure(topLeftRect.BottomLeft, true, true);
                // TopLeft Arc
                context.ArcTo(topLeftRect.TopRight, topLeftRect.Size, 0, false, SweepDirection.Clockwise, true, true);
                // Top Line
                context.LineTo(topRightRect.TopLeft, true, true);
                // TopRight Arc
                context.ArcTo(topRightRect.BottomRight, topRightRect.Size, 0, false, SweepDirection.Clockwise, true, true);
                // Right Line
                context.LineTo(bottomRightRect.TopRight, true, true);
                // BottomRight Arc
                context.ArcTo(bottomRightRect.BottomLeft, bottomRightRect.Size, 0, false, SweepDirection.Clockwise, true, true);
                // Bottom Line
                context.LineTo(bottomLeftRect.BottomRight, true, true);
                // BottomLeft Arc
                context.ArcTo(bottomLeftRect.TopLeft, bottomLeftRect.Size, 0, false, SweepDirection.Clockwise, true, true);
            }

            return(roundedRectGeometry);
        }
コード例 #25
0
        public void Invalidate()
        {
            //Dispatcher.Invoke(delegate { InvalidateVisual(); });
            DrawingVisual drawingVisual = new DrawingVisual();

            using (DrawingContext drawingContext = drawingVisual.RenderOpen())
            {
                //
                // ... draw on the drawingContext
                //
                var            height         = ActualHeight;
                var            med            = height / 2;
                StreamGeometry streamGeometry = new StreamGeometry();
                //RenderOptions.SetEdgeMode(this, EdgeMode.Aliased);

                drawingContext.DrawLine(
                    new Pen(new SolidColorBrush(Color.FromArgb(255, 192, 192, 192)), 1),
                    new Point(0, med - med / 2),
                    new Point(ActualWidth, med - med / 2));

                drawingContext.DrawLine(
                    new Pen(new SolidColorBrush(Color.FromArgb(255, 192, 192, 192)), 1),
                    new Point(0, med + med / 2),
                    new Point(ActualWidth, med + med / 2));

                drawingContext.DrawLine(
                    new Pen(new SolidColorBrush(Color.FromArgb(255, 0, 0, 235)), 1),
                    new Point(0, med),
                    new Point(ActualWidth, med));

                if (PositiveSamples.Count > 0)
                {
                    using (StreamGeometryContext geometryContext = streamGeometry.Open())
                    {
                        PointCollection pcn = new PointCollection(), pcp = new PointCollection();
                        double          deltaX          = (double)ActualWidth / NegativeSamples.Count;
                        double          normalizeFactor = NegativeSamples.Max(a => Math.Abs(a)) / ((double)height / 2);
                        normalizeFactor *= 1.2;
                        geometryContext.BeginFigure(new Point(0, med), false, false);
                        for (int x = 0, n = PositiveSamples.Count; x < n; x++)
                        {
                            //geometryContext.LineTo(new Point(x * deltaX, med), true, true);
                            geometryContext.LineTo(new Point(x * deltaX, med - (PositiveSamples[x] / normalizeFactor)), true, true);

                            //geometryContext.LineTo(new Point(x * deltaX, med), true, true);
                            geometryContext.LineTo(new Point(x * deltaX, med - (NegativeSamples[x] / normalizeFactor)), true, true);
                        }
                    }
                }

                drawingContext.DrawGeometry(
                    new SolidColorBrush(Color.FromArgb(255, 215, 215, 215)),
                    new Pen(new SolidColorBrush(Color.FromArgb(255, 0, 0, 90)), 1),
                    streamGeometry);

                /* if (PositiveSamples.Count > 0)
                 *   using (StreamGeometryContext geometryContext = streamGeometry.Open())
                 *   {
                 *       PointCollection pcn = new PointCollection(), pcp = new PointCollection();
                 *       double i = 0.0;
                 *       double step = ((int)RESOLUTION / ActualWidth);
                 *       step = step < 0 ? 1 : step;
                 *       //bool isNeg = false;
                 *       //double epsilon = 0.01;
                 *       double deltaX = (double)ActualWidth / NegativeSamples.Count;
                 *       double normalizeFactor = NegativeSamples.Max(a => Math.Abs(a)) / ((double)height / 2);
                 *
                 *       geometryContext.BeginFigure(new Point(0, med), false, false);
                 *
                 *       for (int x = 0, n = NegativeSamples.Count; x < n; x++)
                 *       {
                 *           geometryContext.LineTo(new Point(x * deltaX, med), true, true);
                 *           geometryContext.LineTo(new Point(x * deltaX, med - (NegativeSamples[x] / normalizeFactor)), true, true);
                 *       }
                 *       for (int x = 0, n = PositiveSamples.Count; x < n; x++)
                 *       {
                 *           geometryContext.LineTo(new Point(x * deltaX, med), true, true);
                 *           geometryContext.LineTo(new Point(x * deltaX, med - (PositiveSamples[x] / normalizeFactor)), true, true);
                 *       }
                 *       for (int x = 1; x < ActualWidth; x++)
                 *       {
                 *           i += step;
                 *           int j = (int)i;
                 *           if (j >= NegativeSamples.Count)
                 *               j = NegativeSamples.Count - 1;
                 *
                 *
                 *           geometryContext.LineTo(new Point(x, (NegativeSamples[j]) * -(med - med/100*20) + med), true, true);
                 *           geometryContext.LineTo(new Point(x, (PositiveSamples[j]) * -(med - med / 100 * 20) + med), true, true);
                 *
                 *           //if (isNeg)
                 *           //{
                 *           //    pcn.Add(new Point(x, (NegativeSamples[j] * 0.85) * -med + med));
                 *           //    geometryContext.LineTo(new Point(x, (NegativeSamples[j] * 0.85) * -med + med), true, true);
                 *           //    isNeg = Math.Abs(NegativeSamples[j]) < epsilon;
                 *           //}
                 *           //else
                 *           //{
                 *           //    pcn.Add(new Point(x, (PositiveSamples[j] * 0.85) * -med + med));
                 *           //    geometryContext.LineTo(new Point(x, (PositiveSamples[j] * 0.85) * -med + med), true, true);
                 *           //    isNeg = Math.Abs(PositiveSamples[j]) > epsilon;
                 *           //}
                 *
                 *           ////pcn.Add(new Point(x - 1, (NegativeSamples[j - 1] * 0.85) * -med + (med)));
                 *           //pcn.Add(new Point(x, (NegativeSamples[j] * 0.85) * -med + med));
                 *           //pcn.Add(new Point(x, (PositiveSamples[j] * 0.85) * -med + med));
                 *           ////pcn.Add(new Point(x - 1, (PositiveSamples[j - 1] * 0.85) * -med + (med)));
                 *
                 *       }
                 *
                 *      // drawingContext.DrawGeometry(Brushes.LightGreen, new Pen(Brushes.White, 1), streamGeometry);
                 *      // geometryContext.BeginFigure(new Point(0, med), false, false);
                 *      // geometryContext.PolyLineTo(pcn, true, false);
                 *
                 *       drawingContext.DrawGeometry(
                 *           new SolidColorBrush(Color.FromArgb(255, 215, 215, 215)),
                 *           new Pen(new SolidColorBrush(Color.FromArgb(255, 0, 0, 90)), 1),
                 *           streamGeometry);
                 *
                 *       //var image = BitmapToImageSource(GetSignalImage(PositiveSamples.ToArray(), (int)ActualWidth, (int)ActualHeight));
                 *
                 *       //ImageVisual.Source = (ImageSource)image;
                 *
                 *   }
                 */


                drawingContext.Close();

                var bmp = GetImage(drawingVisual);
                ImageVisual.Source = (ImageSource)bmp;



                //var tmpfile = System.IO.Path.GetTempFileName();
                //using (var pngFile = System.IO.File.OpenWrite(tmpfile))
                //    SaveAsPng(bmp, pngFile);

                //var bitmapImage = new BitmapImage();
                //var bitmapEncoder = new PngBitmapEncoder();
                //bitmapEncoder.Frames.Add(BitmapFrame.Create(bmp));
                //using (var stream = new MemoryStream())
                //{
                //    bitmapEncoder.Save(stream);
                //    stream.Seek(0, SeekOrigin.Begin);

                //    bitmapImage.BeginInit();
                //    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                //    bitmapImage.StreamSource = stream;
                //    bitmapImage.EndInit();
                //}
            }
        }
コード例 #26
0
        private static void GenerateGeometry(StreamGeometryContext ctx, Rect rect, SuperRoundedRectRenderer.Radii radii)
        {
            Point point1 = new Point(radii.LeftTop, 0.0);
            Point point2 = new Point(rect.Width - radii.RightTop, 0.0);
            Point point3 = new Point(rect.Width, radii.TopRight);
            Point point4 = new Point(rect.Width, rect.Height - radii.BottomRight);
            Point point5 = new Point(rect.Width - radii.RightBottom, rect.Height);
            Point point6 = new Point(radii.LeftBottom, rect.Height);
            Point point7 = new Point(0.0, rect.Height - radii.BottomLeft);
            Point point8 = new Point(0.0, radii.TopLeft);

            if (point1.X > point2.X)
            {
                double num = radii.LeftTop / (radii.LeftTop + radii.RightTop) * rect.Width;
                point1.X = num;
                point2.X = num;
            }
            if (point3.Y > point4.Y)
            {
                double num = radii.TopRight / (radii.TopRight + radii.BottomRight) * rect.Height;
                point3.Y = num;
                point4.Y = num;
            }
            if (point5.X < point6.X)
            {
                double num = radii.LeftBottom / (radii.LeftBottom + radii.RightBottom) * rect.Width;
                point5.X = num;
                point6.X = num;
            }
            if (point7.Y < point8.Y)
            {
                double num = radii.TopLeft / (radii.TopLeft + radii.BottomLeft) * rect.Height;
                point7.Y = num;
                point8.Y = num;
            }
            Vector vector = new Vector(rect.TopLeft.X, rect.TopLeft.Y);

            point1 += vector;
            point2 += vector;
            point3 += vector;
            point4 += vector;
            point5 += vector;
            point6 += vector;
            point7 += vector;
            point8 += vector;
            ctx.BeginFigure(point1, true, true);
            ctx.LineTo(point2, true, false);
            double num1 = rect.TopRight.X - point2.X;
            double num2 = point3.Y - rect.TopRight.Y;

            if (!Tolerances.NearZero(num1) || !Tolerances.NearZero(num2))
            {
                ctx.ArcTo(point3, new Size(num1, num2), 0.0, false, SweepDirection.Clockwise, true, false);
            }
            ctx.LineTo(point4, true, false);
            double num3 = rect.BottomRight.X - point5.X;
            double num4 = rect.BottomRight.Y - point4.Y;

            if (!Tolerances.NearZero(num3) || !Tolerances.NearZero(num4))
            {
                ctx.ArcTo(point5, new Size(num3, num4), 0.0, false, SweepDirection.Clockwise, true, false);
            }
            ctx.LineTo(point6, true, false);
            double num5 = point6.X - rect.BottomLeft.X;
            double num6 = rect.BottomLeft.Y - point7.Y;

            if (!Tolerances.NearZero(num5) || !Tolerances.NearZero(num6))
            {
                ctx.ArcTo(point7, new Size(num5, num6), 0.0, false, SweepDirection.Clockwise, true, false);
            }
            ctx.LineTo(point8, true, false);
            double num7 = point1.X - rect.TopLeft.X;
            double num8 = point8.Y - rect.TopLeft.Y;

            if (Tolerances.NearZero(num7) && Tolerances.NearZero(num8))
            {
                return;
            }
            ctx.ArcTo(point1, new Size(num7, num8), 0.0, false, SweepDirection.Clockwise, true, false);
        }
コード例 #27
0
        public void PrintLines()
        {
            HideLines();
            ModelNode prev = null;

            _line = new List <UIElement>();
            Pathdic.Clear();
            int i = 0;

            foreach (var machine in _nodes)
            {
                if (prev != null)
                {
                    int linenr = 0;
                    foreach (var relatedProduct in machine.Key.ResourceModel.RelatedProducts)
                    {
                        if (relatedProduct == this)
                        {
                            break;
                        }
                        linenr++;
                    }
                    var b = new Point(prev.Margin.Left + prev.RenderTransform.Value.OffsetX + prev.ActualWidth / 2,
                                      prev.Margin.Top + prev.RenderTransform.Value.OffsetY + prev.ActualHeight / 2 - 10);
                    var a = new Point(
                        machine.Key.Margin.Left + machine.Key.RenderTransform.Value.OffsetX + machine.Key.ActualWidth / 2,
                        machine.Key.Margin.Top + machine.Key.RenderTransform.Value.OffsetY + machine.Key.ActualHeight / 2 - 10);

                    var    dx     = b.X - a.X;
                    var    dy     = b.Y - a.Y;
                    double answer = 0;
                    if (dx == 0 && dy == 0)
                    {
                        answer = 0;
                    }
                    else if (dx > 0 && dy >= 0)
                    {
                        answer = Math.Atan(dy / dx) + Math.PI / 4;
                    }
                    else if (dx <= 0 && dy > 0)
                    {
                        answer = Math.Atan(dx / dy) + Math.PI / 4;
                    }
                    else if (dx <= 0 && dy <= 0)
                    {
                        answer = Math.Atan(dy / dx) + Math.PI / 4;
                    }
                    else if (dx >= 0 && dy <= 0)
                    {
                        answer = Math.Atan(dy / dx) + Math.PI / 4;
                    }
                    b.X = b.X + (Math.Cos(answer) * linenr * 7);
                    b.Y = b.Y + (Math.Sin(answer) * linenr * 7);
                    a.X = a.X + (Math.Cos(answer) * linenr * 7);
                    a.Y = a.Y + (Math.Sin(answer) * linenr * 7);

                    var g = new StreamGeometry();
                    StreamGeometryContext context = g.Open();
                    context.BeginFigure(b, true, true);
                    context.LineTo(a, true, true);
                    context.Close();

                    var path = new Path();

                    path.MouseRightButtonUp += path_MouseRightButtonUp;
                    path.Data            = g;
                    path.RenderTransform = new TranslateTransform();
                    var copy = new Color {
                        A = 30, B = Color.B, G = Color.G, R = Color.R
                    };
                    Brush v = new LinearGradientBrush(Color, copy, 90);
                    path.Stroke          = v;            //new SolidColorBrush(Colors.BlueViolet);
                    path.StrokeThickness = 2.4;
                    Pathdic.Add(path, i++);
                    _line.Add(path);
                }
                prev = machine.Key;
            }
            if (Grid != null)
            {
                foreach (UIElement path in _line)
                {
                    Grid.Add(path);
                }
            }
        }
コード例 #28
0
        static private void CreateEdgePathFromCurve(StreamGeometryContext context, ICurve iCurve)
        {
            context.BeginFigure(iCurve.Start.ToWpf(), false, false);

            var c = iCurve as Curve;

            if (c != null)
            {
                FillContexForCurve(context, c);
                return;
            }

            var cubicBezierSeg = iCurve as CubicBezierSegment;

            if (cubicBezierSeg != null)
            {
                context.BezierTo(cubicBezierSeg.B(1).ToWpf(), cubicBezierSeg.B(2).ToWpf(), cubicBezierSeg.B(3).ToWpf(), true, false);
                return;
            }

            var ls = iCurve as GeometryLineSegment;

            if (ls != null)
            {
                context.LineTo(ls.End.ToWpf(), true, false);
                return;
            }

            var rr = iCurve as RoundedRect;

            if (rr != null)
            {
                FillContexForCurve(context, rr.Curve);
                return;
            }

            var poly = iCurve as GeometryPolyline;

            if (poly != null)
            {
                FillContexForPolyline(context, poly);
                return;
            }

            var ellipse = iCurve as GeometryEllipse;

            if (ellipse != null)
            {
                //       context.LineTo(Common.WpfPoint(ellipse.End),true,false);
                double            sweepAngle = EllipseSweepAngle(ellipse);
                bool              largeArc   = Math.Abs(sweepAngle) >= Math.PI;
                GeometryRectangle box        = ellipse.FullBox();
                context.ArcTo(ellipse.End.ToWpf(),
                              new Size(box.Width / 2, box.Height / 2),
                              sweepAngle,
                              largeArc,
                              sweepAngle < 0
                                    ? SweepDirection.Counterclockwise
                                    : SweepDirection.Clockwise,
                              true, true);

                return;
            }
            else
            {
                throw new NotImplementedException($"{iCurve.GetType()}");
            }
        }
コード例 #29
0
        // x y0 y1 y2 ...
        public void DrawLines(List <double> line, int yCount, string[] curveLabels = null)
        {
            int stride = yCount + 1;

            List <Tuple <Point, string, Pen> > labels = new List <Tuple <Point, string, Pen> >();

            // Draw the lines one by one
            for (int j = 0; j < yCount; j++)
            {
                StreamGeometry geometry = new StreamGeometry();

                StreamGeometryContext ctx = geometry.Open();

                Point  p     = new Point();
                Point  p0    = new Point();
                double alloc = 0;

                for (int i = 0; i < line.Count; i += stride)
                {
                    p = new Point(MapX(line[i]), MapY(alloc = line[i + 1 + j]));

                    if (i == 0)
                    {
                        ctx.BeginFigure(p, false, false);
                        p0 = p;
                    }
                    else
                    {
                        if (Diff(p, p0) >= 0.1) // 1 pixel in 960 dpi
                        {
                            ctx.LineTo(p, true, true);
                            p0 = p;
                        }
                    }
                }

                ctx.Close();

                ColorScheme pal = m_Palettes[j];

                geometry.Freeze();

                m_context.DrawGeometry(null, curveLabels == null ? pal.memoryPen2 : pal.memoryPen1, geometry);

                labels.Add(new Tuple <Point, string, Pen>(
                               p,
                               String.Format("{0} {1:N3} mb", curveLabels == null ? pal.label : curveLabels[j], alloc),
                               pal.memoryPen2));
            }

            double y = m_yAxis - 8;

            foreach (var v in labels.OrderByDescending(v => v.Item1.Y))
            {
                if (v.Item1.Y < y)
                {
                    y = v.Item1.Y;
                }

                m_context.DrawLine(v.Item3, new Point(v.Item1.X + 3, v.Item1.Y), new Point(v.Item1.X + 8, y));

                DrawText(v.Item1.X + 10, y - 5, v.Item2, 10);

                y -= 10;
            }
        }
コード例 #30
0
 public void BeginRead(int contourCount)
 {
     _context = _path.Open();
 }
コード例 #31
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            double          minimum               = this.Minimum;
            double          maximum               = this.Maximum;
            double          tickFrequency         = this.TickFrequency;
            double          majorTickFrequency    = this.MinTicksCount;
            double          majorTickValuesOffset = this.MajorTicksOffset;
            double          startAngle            = base.StartAngle;
            double          endAngle              = base.EndAngle;
            double          ringThickness         = base.RingThickness;
            double          scale     = (endAngle - startAngle) / (maximum - minimum);
            var             stops     = this.RangeColors;
            Point           point     = new Point(base.ActualWidth / 2.0, base.ActualHeight);
            RotateTransform transform = new RotateTransform(0.0, point.X, point.Y);
            Point           point2    = new Point(point.X, 0.0);
            Point           point3    = new Point(point.X, ringThickness);
            Point           point4    = new Point(point.X, ringThickness / 2);

            if (stops.Count != 0)
            {
                double x          = 0.0;
                double angle      = 90 - endAngle;
                Color  startColor = stops[0].Color;
                Color  color      = stops[0].Color;
                Size   size       = new Size(point.X, point.Y);
                Size   size2      = new Size(Math.Abs(size.Width - ringThickness), Math.Abs(size.Height - ringThickness));
                for (int i = 0; i <= stops.Count; i++)
                {
                    double scaleAngle;
                    if (i < stops.Count)
                    {
                        double offset = stops[i].Offset;
                        if (offset > maximum)
                        {
                            offset = maximum;
                        }
                        scaleAngle = (offset - x) * scale;
                        x          = offset;
                        color      = stops[i].Color;
                    }
                    else
                    {
                        scaleAngle = (maximum - x) * scale;
                        x          = maximum;
                    }
                    RotateTransform transform1 = new RotateTransform(angle, point.X, point.Y);
                    transform1.Angle = scaleAngle;
                    Point                 point14  = transform1.Transform(point2);
                    Point                 point15  = transform1.Transform(point3);
                    StreamGeometry        geometry = new StreamGeometry();
                    StreamGeometryContext context  = geometry.Open();
                    context.BeginFigure(point2, true, true);
                    context.ArcTo(point14, size, 0.0, scaleAngle > 180.0, SweepDirection.Clockwise, true, true);
                    context.LineTo(point15, true, true);
                    context.ArcTo(point3, size2, 0.0, scaleAngle > 180.0, SweepDirection.Counterclockwise, true, true);
                    context.Close();
                    geometry.Freeze();
                    transform1 = new RotateTransform(angle + (scaleAngle / 2.0), 0.5, 0.5);
                    point2     = transform1.Transform(new Point(0.0, 0.5));
                    point14    = transform1.Transform(new Point(1.0, 0.5));
                    drawingContext.DrawGeometry(new LinearGradientBrush(startColor, color, point2, point14), null, geometry);
                    if (x >= maximum)
                    {
                        break;
                    }
                    startColor = color;
                    angle     += scaleAngle;
                }
            }
            if (tickFrequency > 0.0)
            {
                double num1 = tickFrequency - (Math.Truncate((tickFrequency - minimum) / tickFrequency) * tickFrequency);
                transform.Angle = 90 - endAngle - ((num1 - minimum) * scale);
                Pen pen = new Pen(base.Foreground, base.StrokeThickness);
                while (num1 <= maximum)
                {
                    drawingContext.DrawLine(pen, transform.Transform(point2), transform.Transform(point4));
                    num1            += tickFrequency;
                    transform.Angle += tickFrequency * scale;
                }
            }
            if (majorTickFrequency > 0.0)
            {
                int    index = 0;
                double num1  = majorTickFrequency - (Math.Truncate((majorTickFrequency - minimum) / majorTickFrequency) * majorTickFrequency);
                transform.Angle = 90 - endAngle - ((num1 - minimum) * scale);
                Point  point5 = new Point(point.X, majorTickValuesOffset);
                Pen    pen2   = new Pen(base.Foreground, base.StrokeThickness * 2.0);
                double scaleX = 1.0;
                double scaleY = 1.0;
                var    ticks  = this.Ticks;
                while (num1 <= maximum)
                {
                    string text;
                    drawingContext.DrawLine(pen2, transform.Transform(point2), transform.Transform(point3));
                    if (ticks != null && index < ticks.Count)
                    {
                        text = ticks[index].ToString();;
                    }
                    else
                    {
                        text = num1.ToString(this.TickStringFormat);
                    }
                    FormattedText formattedText = new FormattedText(text, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight,
                                                                    new Typeface(base.FontFamily, base.FontStyle, base.FontWeight, base.FontStretch), base.FontSize, base.Foreground);
                    Point origin = transform.Transform(point5);
                    drawingContext.PushTransform(new ScaleTransform(scaleX, scaleY, origin.X, origin.Y));
                    origin.X -= formattedText.Width / 2.0;
                    origin.Y -= formattedText.Height / 2.0;
                    drawingContext.DrawText(formattedText, origin);
                    drawingContext.Pop();
                    num1            += majorTickFrequency;
                    transform.Angle += majorTickFrequency * scale;
                    index++;
                }
            }
        }
コード例 #32
0
                public bool UpdateGeometry(double X, double Y, Point mousePos, double zoomFactor, bool bForceUpdate, Int64 timeStepMS)
                {
                    bool bUpdatedGeometry = false;

                    if (UpdateIntenalState(mousePos) || bForceUpdate)
                    {
                        bUpdatedGeometry = true;

                        if (_enabled && _samples.Count > 0)
                        {
                            CalculateGraphPoints(GraphMode.AverageValues, X, Y, zoomFactor, timeStepMS);

                            if (_points.Count >= 2)
                            {
                                // Clear old geometry
                                _geometry.Clear();

                                _selectedGraphPoint = null;

                                using (StreamGeometryContext ctx = _geometry.Open())
                                {
                                    for (int i = 0; i + 1 < _points.Count; ++i)
                                    {
                                        GraphPoint P1 = _points[i];
                                        GraphPoint P2 = _points[i + 1];
                                        if (IsPointVisible(P1._coordinates) || IsPointVisible(P2._coordinates))
                                        {
                                            GraphPoint selectedGraphPoint = IsMousePosWithinSegment(mousePos, P1, P2);

                                            if (selectedGraphPoint != null && SystemPerformanceGraphsCanvas._hasSelectedGraphPoint == false)
                                            {
                                                _selectedGraphPoint = selectedGraphPoint;

                                                DrawFilledSquare(ctx, _selectedGraphPoint._coordinates, 10);

                                                SystemPerformanceGraphsCanvas._hasSelectedGraphPoint = true;
                                            }

                                            ctx.BeginFigure(P1._coordinates, true /* is filled */, false /* is closed */);

                                            ctx.LineTo(P2._coordinates, true /* is stroked */, false /* is smooth join */);
                                        }
                                    }
                                }


                                if (_selectedGraphPoint != null)
                                {
                                    using (StreamGeometryContext ctx = _selectionLinesGeometry.Open())
                                    {
                                        ctx.BeginFigure(new Point(SystemPerformanceGraphsCanvas._savedHorizontalViewport.X, _selectedGraphPoint._coordinates.Y), false /* is filled */, false /* is closed */);

                                        ctx.LineTo(new Point(_selectedGraphPoint._coordinates.X, _selectedGraphPoint._coordinates.Y), true /* is stroked */, false /* is smooth join */);

                                        ctx.LineTo(new Point(_selectedGraphPoint._coordinates.X, SystemPerformanceGraphsCanvas.cSystemGraphsHeight), true /* is stroked */, false /* is smooth join */);
                                    }
                                }
                                else
                                {
                                    _selectionLinesGeometry.Clear();
                                }
                            }
                        }
                        else
                        {
                            // Clear old geometry
                            _geometry.Clear();
                        }
                    }

                    return(bUpdatedGeometry);
                }
コード例 #33
0
ファイル: ClipBorder.cs プロジェクト: wqshabib/wpfspark
        /// <summary>
        ///     Generates a StreamGeometry.
        /// </summary>
        /// <param name="ctx">An already opened StreamGeometryContext.</param>
        /// <param name="rect">Rectangle for geomentry conversion.</param>
        /// <param name="borderInfo">The core points of the border which needs to be used to create
        /// the geometry</param>
        /// <returns>Result geometry.</returns>
        private static void GenerateGeometry(StreamGeometryContext ctx, Rect rect, BorderInfo borderInfo)
        {
            //  compute the coordinates of the key points
            var leftTop     = new Point(borderInfo.LeftTop, 0);
            var rightTop    = new Point(rect.Width - borderInfo.RightTop, 0);
            var topRight    = new Point(rect.Width, borderInfo.TopRight);
            var bottomRight = new Point(rect.Width, rect.Height - borderInfo.BottomRight);
            var rightBottom = new Point(rect.Width - borderInfo.RightBottom, rect.Height);
            var leftBottom  = new Point(borderInfo.LeftBottom, rect.Height);
            var bottomLeft  = new Point(0, rect.Height - borderInfo.BottomLeft);
            var topLeft     = new Point(0, borderInfo.TopLeft);

            //  check keypoints for overlap and resolve by partitioning corners according to
            //  the percentage of each one.

            //  top edge
            if (leftTop.X > rightTop.X)
            {
                var v = (borderInfo.LeftTop) / (borderInfo.LeftTop + borderInfo.RightTop) * rect.Width;
                leftTop.X  = v;
                rightTop.X = v;
            }

            //  right edge
            if (topRight.Y > bottomRight.Y)
            {
                var v = (borderInfo.TopRight) / (borderInfo.TopRight + borderInfo.BottomRight) * rect.Height;
                topRight.Y    = v;
                bottomRight.Y = v;
            }

            //  bottom edge
            if (leftBottom.X > rightBottom.X)
            {
                var v = (borderInfo.LeftBottom) / (borderInfo.LeftBottom + borderInfo.RightBottom) * rect.Width;
                rightBottom.X = v;
                leftBottom.X  = v;
            }

            // left edge
            if (topLeft.Y > bottomLeft.Y)
            {
                var v = (borderInfo.TopLeft) / (borderInfo.TopLeft + borderInfo.BottomLeft) * rect.Height;
                bottomLeft.Y = v;
                topLeft.Y    = v;
            }

            // Apply offset
            var offsetX = rect.TopLeft.X;
            var offsetY = rect.TopLeft.Y;
            var offset  = new Vector(offsetX, offsetY);

            leftTop     += offset;
            rightTop    += offset;
            topRight    += offset;
            bottomRight += offset;
            rightBottom += offset;
            leftBottom  += offset;
            bottomLeft  += offset;
            topLeft     += offset;

            //  create the border geometry
            ctx.BeginFigure(leftTop, true /* is filled */, true /* is closed */);

            // Top line
            ctx.LineTo(rightTop, true /* is stroked */, false /* is smooth join */);

            // Upper-right corners
            var radiusX = rect.TopRight.X - rightTop.X;
            var radiusY = topRight.Y - rect.TopRight.Y;

            if (!radiusX.IsZero() || !radiusY.IsZero())
            {
                ctx.ArcTo(topRight, new Size(radiusX, radiusY), 0, false, SweepDirection.Clockwise, true, false);
            }

            // Right line
            ctx.LineTo(bottomRight, true /* is stroked */, false /* is smooth join */);

            // Lower-right corners
            radiusX = rect.BottomRight.X - rightBottom.X;
            radiusY = rect.BottomRight.Y - bottomRight.Y;
            if (!radiusX.IsZero() || !radiusY.IsZero())
            {
                ctx.ArcTo(rightBottom, new Size(radiusX, radiusY), 0, false, SweepDirection.Clockwise, true, false);
            }

            // Bottom line
            ctx.LineTo(leftBottom, true /* is stroked */, false /* is smooth join */);

            // Lower-left corners
            radiusX = leftBottom.X - rect.BottomLeft.X;
            radiusY = rect.BottomLeft.Y - bottomLeft.Y;
            if (!radiusX.IsZero() || !radiusY.IsZero())
            {
                ctx.ArcTo(bottomLeft, new Size(radiusX, radiusY), 0, false, SweepDirection.Clockwise, true, false);
            }

            // Left line
            ctx.LineTo(topLeft, true /* is stroked */, false /* is smooth join */);

            // Upper-left corners
            radiusX = leftTop.X - rect.TopLeft.X;
            radiusY = topLeft.Y - rect.TopLeft.Y;
            if (!radiusX.IsZero() || !radiusY.IsZero())
            {
                ctx.ArcTo(leftTop, new Size(radiusX, radiusY), 0, false, SweepDirection.Clockwise, true, false);
            }
        }
コード例 #34
0
        internal static void Deserialize(BinaryReader br, StreamGeometryContext sc, StreamGeometry geometry)
        {
            bool closed = false;
            Byte currentByte;

            while (!closed)
            {
                currentByte = br.ReadByte();

                ParserGeometryContextOpCodes opCode = UnPackOpCode(currentByte);

                switch(opCode)
                {
                    case ParserGeometryContextOpCodes.FillRule :
                        DeserializeFillRule(br, currentByte, geometry);
                        break;

                    case ParserGeometryContextOpCodes.BeginFigure :
                        DeserializeBeginFigure(br, currentByte, sc);
                        break;

                    case ParserGeometryContextOpCodes.LineTo :
                        DeserializeLineTo(br, currentByte, sc);
                        break;

                    case ParserGeometryContextOpCodes.QuadraticBezierTo :
                        DeserializeQuadraticBezierTo(br, currentByte, sc);
                        break;

                    case ParserGeometryContextOpCodes.BezierTo :
                        DeserializeBezierTo(br, currentByte, sc);
                        break;

                    case ParserGeometryContextOpCodes.PolyLineTo :
                        DeserializePolyLineTo(br, currentByte, sc);
                        break;

                    case ParserGeometryContextOpCodes.PolyQuadraticBezierTo :
                        DeserializePolyQuadraticBezierTo(br, currentByte, sc);
                        break;

                    case ParserGeometryContextOpCodes.PolyBezierTo :
                        DeserializePolyBezierTo(br, currentByte, sc);
                        break;

                    case ParserGeometryContextOpCodes.ArcTo :
                        DeserializeArcTo(br, currentByte, sc);
                        break;

                    case ParserGeometryContextOpCodes.Closed :
                        closed = true;
                        break;
                }
            }
        }
コード例 #35
0
 public static void BeginFigure(this StreamGeometryContext context, Point point, bool isFilled)
 {
     context.BeginFigure(point, isFilled, isClosed: false);
 }
コード例 #36
0
        private static void DeserializeLineTo(BinaryReader br, Byte firstByte, StreamGeometryContext sc)
        {
            Point point;
            bool isStroked;
            bool isSmoothJoin;

            DeserializePointAndTwoBools(br, firstByte, out point, out isStroked, out isSmoothJoin);

            sc.LineTo(point, isStroked, isSmoothJoin);
        }
コード例 #37
0
ファイル: SwitchButton.cs プロジェクト: llorch19/H.Framework
        private void DrawButtons(DrawingContext dc, int count)
        {
            double          transformAngle = -90 - 360 / count / 2;
            RotateTransform tf             = new RotateTransform(transformAngle)
            {
                CenterX = Width / 2, CenterY = Height / 2
            };

            dc.PushTransform(tf);
            for (int j = 0; j < count; j++)
            {
                StreamGeometry  streamGeometry = new StreamGeometry();
                PointCollection points         = new PointCollection();
                int             preP           = 360 / count * j;
                int             toP            = 360 / count * (j + 1);
                using (StreamGeometryContext geometryContext = streamGeometry.Open())
                {
                    for (int i = preP; i <= toP; i++)
                    {
                        double theta = Math.PI * (i / 180.0);
                        double oy, ox;
                        if (j == _selectIndex)
                        {
                            oy = Height / 2 + (_outSize * _selectZoomScale * Math.Sin(theta));
                            ox = Width / 2 + (_outSize * _selectZoomScale * Math.Cos(theta));
                        }
                        else
                        {
                            oy = Height / 2 + (_outSize * Math.Sin(theta));
                            ox = Width / 2 + (_outSize * Math.Cos(theta));
                        }

                        Point p = new Point(ox, oy);
                        if (i == preP)
                        {
                            geometryContext.BeginFigure(p, true, true);
                        }
                        else
                        {
                            points.Add(p);
                        }
                    }

                    for (int k = toP - 1; k >= preP; k--)
                    {
                        double theta = Math.PI * (k / 180.0);
                        double iy    = Height / 2 + (_innerCircleSize * Math.Sin(theta));
                        double ix    = Width / 2 + (_innerCircleSize * Math.Cos(theta));
                        Point  p     = new Point(ix, iy);
                        points.Add(p);
                    }
                    geometryContext.PolyLineTo(points, true, true);
                }
                if (!_hasAdded)
                {
                    _allButtons.Add(points);
                }
                if (_selectIndex == j)
                {
                    if (j == _defaultButtonIndex)
                    {
                        dc.DrawGeometry(new SolidColorBrush(DefaultButtonSelectColor), new Pen(new SolidColorBrush(DefaultButtonBorderColor), ButtonBorderWidth), streamGeometry);
                    }
                    else
                    {
                        dc.DrawGeometry(new SolidColorBrush(ButtonSelectColor), new Pen(new SolidColorBrush(ButtonBorderColor), ButtonBorderWidth), streamGeometry);
                    }
                }
                else
                {
                    if (j == _defaultButtonIndex)
                    {
                        dc.DrawGeometry(new SolidColorBrush(DefaultButtonColor), new Pen(new SolidColorBrush(DefaultButtonBorderColor), ButtonBorderWidth), streamGeometry);
                    }
                    else
                    {
                        dc.DrawGeometry(new SolidColorBrush(ButtonColor), new Pen(new SolidColorBrush(ButtonBorderColor), ButtonBorderWidth), streamGeometry);
                    }
                }
            }
            dc.Pop();
            for (int i = 0; i < count; i++)
            {
                if (i >= _buttonValues.Count)
                {
                    break;
                }
                int    preP = 360 / count * i;
                int    toP = 360 / count * (i + 1);
                double ca = ((toP + preP) / 2.0 + transformAngle) % 360;
                double theta = Math.PI * (ca / 180.0);
                double oy, ox;
                if (_selectIndex == i)
                {
                    oy = Height / 2 + (_outSize * _selectZoomScale * Math.Sin(theta));
                    ox = Width / 2 + (_outSize * _selectZoomScale * Math.Cos(theta));
                }
                else
                {
                    oy = Height / 2 + (_outSize * Math.Sin(theta));
                    ox = Width / 2 + (_outSize * Math.Cos(theta));
                }
                double          iy     = Height / 2 + (_innerCircleSize * Math.Sin(theta));
                double          ix     = Width / 2 + (_innerCircleSize * Math.Cos(theta));
                double          length = Math.Sqrt(Math.Pow(ox - ix, 2) + Math.Pow(oy - iy, 2));
                Size            s      = ComputeRect(_buttonValues[i], _fontSize);
                double          fh     = s.Height / 2;
                double          pers   = fh / length + 0.5;
                Point           cp     = new Point(ix + (ox - ix) * pers, iy + (oy - iy) * pers);
                RotateTransform tf1    = new RotateTransform(ca + 90)
                {
                    CenterX = cp.X, CenterY = cp.Y
                };
                dc.PushTransform(tf1);
                if (_selectIndex == i)
                {
                    if (i == _defaultButtonIndex)
                    {
                        if (i < _buttonValues.Count)
                        {
                            dc.DrawText(CreateTextFormat(_buttonValues[i], DefaultButtonSelectTextColor, _fontSize + 3, FlowDirection.LeftToRight), cp);
                        }
                    }
                    else
                    {
                        if (i < _buttonValues.Count)
                        {
                            dc.DrawText(CreateTextFormat(_buttonValues[i], ButtonSelectTextColor, _fontSize + 3, FlowDirection.LeftToRight), cp);
                        }
                    }
                }
                else
                {
                    if (i == _defaultButtonIndex)
                    {
                        if (i < _buttonValues.Count)
                        {
                            dc.DrawText(CreateTextFormat(_buttonValues[i], DefaultButtonTextColor, _fontSize, FlowDirection.LeftToRight), cp);
                        }
                    }
                    else
                    {
                        if (i < _buttonValues.Count)
                        {
                            dc.DrawText(CreateTextFormat(_buttonValues[i], ButtonTextColor, _fontSize, FlowDirection.LeftToRight), cp);
                        }
                    }
                }
                dc.Pop();
            }
            _hasAdded = true;

            DrawTrackLine(dc);
        }
コード例 #38
0
        private static void DeserializePolyBezierTo(BinaryReader br, Byte firstByte, StreamGeometryContext sc)
        {
            bool isStroked;
            bool isSmoothJoin;
            IList<Point> points;

            points = DeserializeListOfPointsAndTwoBools(br, firstByte, out isStroked, out isSmoothJoin);

            sc.PolyBezierTo(points, isStroked, isSmoothJoin);
        }
コード例 #39
0
ファイル: GestureImage.cs プロジェクト: zhaokeli/GestureSign
        public static DrawingImage CreateImage(PointPattern[] pointPatterns, Size size, Color color)
        {
            if (pointPatterns == null)
            {
                return(null);
            }

            DrawingGroup drawingGroup = new DrawingGroup();

            for (int i = 0; i < pointPatterns.Length; i++)
            {
                PathGeometry pathGeometry = new PathGeometry();

                color.A = (byte)(0xFF - i * 0x55);
                SolidColorBrush brush      = new SolidColorBrush(color);
                Pen             drawingPen = new Pen(brush, size.Height / 20 + i * 1.5)
                {
                    StartLineCap = PenLineCap.Round, EndLineCap = PenLineCap.Round
                };

                if (pointPatterns[i].Points == null)
                {
                    return(null);
                }
                for (int j = 0; j < pointPatterns[i].Points.Count; j++)
                {
                    if (pointPatterns[i].Points[j].Count == 1)
                    {
                        Geometry ellipse = new EllipseGeometry(new Point(size.Width * j + size.Width / 2, size.Height / 2),
                                                               drawingPen.Thickness / 2, drawingPen.Thickness / 2);
                        pathGeometry.AddGeometry(ellipse);
                        continue;
                    }
                    StreamGeometry sg = new StreamGeometry {
                        FillRule = FillRule.EvenOdd
                    };
                    using (StreamGeometryContext sgc = sg.Open())
                    {
                        // Create new size object accounting for pen width
                        Size szeAdjusted = new Size(size.Width - drawingPen.Thickness - 1,
                                                    (size.Height - drawingPen.Thickness - 1));

                        Size    scaledSize;
                        Point[] scaledPoints = ScaleGesture(pointPatterns[i].Points[j], szeAdjusted.Width - 10, szeAdjusted.Height - 10,
                                                            out scaledSize);

                        // Define size that will mark the offset to center the gesture
                        double iLeftOffset = (size.Width / 2) - (scaledSize.Width / 2);
                        double iTopOffset  = (size.Height / 2) - (scaledSize.Height / 2);
                        Vector sizOffset   = new Vector(iLeftOffset + j * size.Width, iTopOffset);
                        sgc.BeginFigure(Point.Add(scaledPoints[0], sizOffset), false, false);
                        foreach (Point p in scaledPoints)
                        {
                            sgc.LineTo(Point.Add(p, sizOffset), true, true);
                        }
                        DrawArrow(sgc, scaledPoints, sizOffset, drawingPen.Thickness);
                    }
                    sg.Freeze();
                    pathGeometry.AddGeometry(sg);
                }
                pathGeometry.Freeze();
                GeometryDrawing drawing = new GeometryDrawing(null, drawingPen, pathGeometry);
                drawing.Freeze();
                drawingGroup.Children.Add(drawing);
            }
            //  myPath.Data = sg;
            drawingGroup.Freeze();
            DrawingImage drawingImage = new DrawingImage(drawingGroup);

            drawingImage.Freeze();

            return(drawingImage);
        }
コード例 #40
0
        private void updatePeakMeter()
        {
            if (m_pcmFormat == null)
            {
                return;
            }
            if (Dispatcher.CheckAccess())
            {
                if (m_Player.State != AudioPlayerState.Playing)
                {
                    return;
                }

                double barWidth = PeakMeterCanvas.ActualWidth;
                if (m_pcmFormat.NumberOfChannels > 1)
                {
                    barWidth = barWidth / 2;
                }
                double availableHeight = PeakMeterCanvas.ActualHeight;

                StreamGeometry geometry1 = null;
                StreamGeometry geometry2 = null;

                if (PeakMeterPathCh1.Data == null)
                {
                    geometry1 = new StreamGeometry();
                }
                else
                {
                    geometry1 = (StreamGeometry)PeakMeterPathCh1.Data;
                    geometry1.Clear();
                }
                using (StreamGeometryContext sgc = geometry1.Open())
                {
                    m_PeakMeterBarDataCh1.ValueDb = m_PeakMeterValues[0];

                    double pixels = m_PeakMeterBarDataCh1.DbToPixels(availableHeight);

                    sgc.BeginFigure(new Point(0, 0), true, true);
                    sgc.LineTo(new Point(barWidth, 0), true, false);
                    sgc.LineTo(new Point(barWidth, availableHeight - pixels), true, false);
                    sgc.LineTo(new Point(0, availableHeight - pixels), true, false);

                    sgc.Close();
                }

                if (m_pcmFormat.NumberOfChannels > 1)
                {
                    if (PeakMeterPathCh2.Data == null)
                    {
                        geometry2 = new StreamGeometry();
                    }
                    else
                    {
                        geometry2 = (StreamGeometry)PeakMeterPathCh2.Data;
                        geometry2.Clear();
                    }
                    using (StreamGeometryContext sgc = geometry2.Open())
                    {
                        m_PeakMeterBarDataCh2.ValueDb = m_PeakMeterValues[1];

                        double pixels = m_PeakMeterBarDataCh2.DbToPixels(availableHeight);

                        sgc.BeginFigure(new Point(barWidth, 0), true, true);
                        sgc.LineTo(new Point(barWidth + barWidth, 0), true, false);
                        sgc.LineTo(new Point(barWidth + barWidth, availableHeight - pixels), true, false);
                        sgc.LineTo(new Point(barWidth, availableHeight - pixels), true, false);
                        sgc.LineTo(new Point(barWidth, availableHeight), true, false);

                        sgc.Close();
                    }
                }


                if (PeakMeterPathCh1.Data == null)
                {
                    PeakMeterPathCh1.Data = geometry1;
                }
                else
                {
                    PeakMeterPathCh1.InvalidateVisual();
                }
                if (m_pcmFormat.NumberOfChannels > 1)
                {
                    if (PeakMeterPathCh2.Data == null)
                    {
                        PeakMeterPathCh2.Data = geometry2;
                    }
                    else
                    {
                        PeakMeterPathCh2.InvalidateVisual();
                    }
                }
            }
            else
            {
                Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadStart(updatePeakMeter));
            }
        }
コード例 #41
0
        private static void CreateGeometry(StreamGeometryContext context, Rect boundRect, BorderCoordinates borderCoordinates)
        {
            var topLeft     = new Point(borderCoordinates.LeftTop, 0);
            var topRight    = new Point(boundRect.Width - borderCoordinates.RightTop, 0);
            var rightTop    = new Point(boundRect.Width, borderCoordinates.TopRight);
            var rightBottom = new Point(boundRect.Width, boundRect.Height - borderCoordinates.BottomRight);
            var bottomRight = new Point(boundRect.Width - borderCoordinates.RightBottom, boundRect.Height);
            var bottomLeft  = new Point(borderCoordinates.LeftBottom, boundRect.Height);
            var leftBottom  = new Point(0, boundRect.Height - borderCoordinates.BottomLeft);
            var leftTop     = new Point(0, borderCoordinates.TopLeft);


            if (topLeft.X > topRight.X)
            {
                var scaledX = borderCoordinates.LeftTop / (borderCoordinates.LeftTop + borderCoordinates.RightTop) * boundRect.Width;
                topLeft  = new Point(scaledX, topLeft.Y);
                topRight = new Point(scaledX, topRight.Y);
            }

            if (rightTop.Y > rightBottom.Y)
            {
                var scaledY = borderCoordinates.TopRight / (borderCoordinates.TopRight + borderCoordinates.BottomRight) * boundRect.Height;
                rightTop    = new Point(rightTop.X, scaledY);
                rightBottom = new Point(rightBottom.X, scaledY);
            }

            if (bottomRight.X < bottomLeft.X)
            {
                var scaledX = borderCoordinates.LeftBottom / (borderCoordinates.LeftBottom + borderCoordinates.RightBottom) * boundRect.Width;
                bottomRight = new Point(scaledX, bottomRight.Y);
                bottomLeft  = new Point(scaledX, bottomLeft.Y);
            }

            if (leftBottom.Y < leftTop.Y)
            {
                var scaledY = borderCoordinates.TopLeft / (borderCoordinates.TopLeft + borderCoordinates.BottomLeft) * boundRect.Height;
                leftBottom = new Point(leftBottom.X, scaledY);
                leftTop    = new Point(leftTop.X, scaledY);
            }

            var offset = new Vector(boundRect.TopLeft.X, boundRect.TopLeft.Y);

            topLeft     += offset;
            topRight    += offset;
            rightTop    += offset;
            rightBottom += offset;
            bottomRight += offset;
            bottomLeft  += offset;
            leftBottom  += offset;
            leftTop     += offset;

            context.BeginFigure(topLeft, true);

            //Top
            context.LineTo(topRight);

            //TopRight corner
            var radiusX = boundRect.TopRight.X - topRight.X;
            var radiusY = rightTop.Y - boundRect.TopRight.Y;

            if (radiusX != 0 || radiusY != 0)
            {
                context.ArcTo(rightTop, new Size(radiusY, radiusY), 0, false, SweepDirection.Clockwise);
            }

            //Right
            context.LineTo(rightBottom);

            //BottomRight corner
            radiusX = boundRect.BottomRight.X - bottomRight.X;
            radiusY = boundRect.BottomRight.Y - rightBottom.Y;
            if (radiusX != 0 || radiusY != 0)
            {
                context.ArcTo(bottomRight, new Size(radiusX, radiusY), 0, false, SweepDirection.Clockwise);
            }

            //Bottom
            context.LineTo(bottomLeft);

            //BottomLeft corner
            radiusX = bottomLeft.X - boundRect.BottomLeft.X;
            radiusY = boundRect.BottomLeft.Y - leftBottom.Y;
            if (radiusX != 0 || radiusY != 0)
            {
                context.ArcTo(leftBottom, new Size(radiusX, radiusY), 0, false, SweepDirection.Clockwise);
            }

            //Left
            context.LineTo(leftTop);

            //TopLeft corner
            radiusX = topLeft.X - boundRect.TopLeft.X;
            radiusY = leftTop.Y - boundRect.TopLeft.Y;

            if (radiusX != 0 || radiusY != 0)
            {
                context.ArcTo(topLeft, new Size(radiusX, radiusY), 0, false, SweepDirection.Clockwise);
            }

            context.EndFigure(true);
        }
コード例 #42
0
 protected internal override void ApplyTo(StreamGeometryContext ctx)
 {
     ctx.CubicBezierTo(Point1, Point2, Point3);
 }
コード例 #43
0
 protected internal override void ApplyTo(StreamGeometryContext ctx)
 {
     ctx.QuadraticBezierTo(Point1, Point2);
 }