Esempio n. 1
1
        /// <summary>
        /// Renders the matrix code.
        /// </summary>
        protected internal override void Render(XGraphics gfx, XBrush brush, XPoint position)
        {
            XGraphicsState state = gfx.Save();

            switch (Direction)
            {
                case CodeDirection.RightToLeft:
                    gfx.RotateAtTransform(180, position);
                    break;

                case CodeDirection.TopToBottom:
                    gfx.RotateAtTransform(90, position);
                    break;

                case CodeDirection.BottomToTop:
                    gfx.RotateAtTransform(-90, position);
                    break;
            }

            XPoint pos = position + CalcDistance(Anchor, AnchorType.TopLeft, Size);

            if (MatrixImage == null)
                MatrixImage = DataMatrixImage.GenerateMatrixImage(Text, Encoding, Rows, Columns);

            if (QuietZone > 0)
            {
                XSize sizeWithZone = new XSize(Size.Width, Size.Height);
                sizeWithZone.Width = sizeWithZone.Width / (Columns + 2 * QuietZone) * Columns;
                sizeWithZone.Height = sizeWithZone.Height / (Rows + 2 * QuietZone) * Rows;

                XPoint posWithZone = new XPoint(pos.X, pos.Y);
                posWithZone.X += Size.Width / (Columns + 2 * QuietZone) * QuietZone;
                posWithZone.Y += Size.Height / (Rows + 2 * QuietZone) * QuietZone;

                gfx.DrawRectangle(XBrushes.White, pos.X, pos.Y, Size.Width, Size.Height);
                gfx.DrawImage(MatrixImage, posWithZone.X, posWithZone.Y, sizeWithZone.Width, sizeWithZone.Height);
            }
            else
                gfx.DrawImage(MatrixImage, pos.X, pos.Y, Size.Width, Size.Height);

            gfx.Restore(state);
        }
Esempio n. 2
0
 public BarCodeRenderInfo(XGraphics gfx, XBrush brush, XFont font, XPoint position)
 {
     Gfx = gfx;
     Brush = brush;
     Font = font;
     Position = position;
 }
Esempio n. 3
0
        /// <summary>
        /// Renders the OMR code.
        /// </summary>
        protected internal override void Render(XGraphics gfx, XBrush brush, XFont font, XPoint position)
        {
            XGraphicsState state = gfx.Save();

            switch (Direction)
            {
                case CodeDirection.RightToLeft:
                    gfx.RotateAtTransform(180, position);
                    break;

                case CodeDirection.TopToBottom:
                    gfx.RotateAtTransform(90, position);
                    break;

                case CodeDirection.BottomToTop:
                    gfx.RotateAtTransform(-90, position);
                    break;
            }

            //XPoint pt = center - size / 2;
            XPoint pt = position - CodeBase.CalcDistance(AnchorType.TopLeft, Anchor, Size);
            uint value;
            uint.TryParse(Text, out value);
#if true
            // HACK: Project Wallenwein: set LK
            value |= 1;
            _synchronizeCode = true;
#endif
            if (_synchronizeCode)
            {
                XRect rect = new XRect(pt.X, pt.Y, _makerThickness, Size.Height);
                gfx.DrawRectangle(brush, rect);
                pt.X += 2 * _makerDistance;
            }
            for (int idx = 0; idx < 32; idx++)
            {
                if ((value & 1) == 1)
                {
                    XRect rect = new XRect(pt.X + idx * _makerDistance, pt.Y, _makerThickness, Size.Height);
                    gfx.DrawRectangle(brush, rect);
                }
                value = value >> 1;
            }
            gfx.Restore(state);
        }
Esempio n. 4
0
 /// <summary>
 /// Multiplies a point with a matrix.
 /// </summary>
 public static XPoint Multiply(XPoint point, XMatrix matrix)
 {
     return(matrix.Transform(point));
 }
Esempio n. 5
0
 /// <summary>
 /// PDFsharp uses the Td operator to set the text position. Td just sets the offset of the text matrix
 /// and produces lesser code as Tm.
 /// </summary>
 /// <param name="pos">The absolute text position.</param>
 /// <param name="dy">The dy.</param>
 /// <param name="adjustSkew">true if skewing for italic simulation is currently on.</param>
 void AdjustTdOffset(ref XPoint pos, double dy, bool adjustSkew)
 {
     pos.Y += dy;
     // Reference: TABLE 5.5  Text-positioning operators / Page 406
     XPoint posSave = pos;
     // Map from absolute to relative position.
     pos = pos - new XVector(_gfxState.RealizedTextPosition.X, _gfxState.RealizedTextPosition.Y);
     if (adjustSkew)
     {
         // In case that italic simulation is on X must be adjusted according to Y offset. Weird but works :-)
         pos.X -= Const.ItalicSkewAngleSinus * pos.Y;
     }
     _gfxState.RealizedTextPosition = posSave;
 }
Esempio n. 6
0
    // ----- DrawCurve ----------------------------------------------------------------------------

    public void DrawCurve(XPen pen, XPoint[] points, double tension)
    {
      if (pen == null)
        throw new ArgumentNullException("pen");
      if (points == null)
        throw new ArgumentNullException("points");

      int count = points.Length;
      if (count == 0)
        return;
      if (count < 2)
        throw new ArgumentException("Not enough points", "points");

      // See http://pubpages.unh.edu/~cs770/a5/cardinal.html
      tension /= 3;

      Realize(pen);

      AppendFormat("{0:0.###} {1:0.###} m\n", points[0].X, points[0].Y);
      if (count == 2)
      {
        // Just draws a line...
        AppendCurveSegment(points[0], points[0], points[1], points[1], tension);
      }
      else
      {
        AppendCurveSegment(points[0], points[0], points[1], points[2], tension);
        for (int idx = 1; idx < count - 2; idx++)
          AppendCurveSegment(points[idx - 1], points[idx], points[idx + 1], points[idx + 2], tension);
        AppendCurveSegment(points[count - 3], points[count - 2], points[count - 1], points[count - 1], tension);
      }
      AppendStrokeFill(pen, null, XFillMode.Alternate, false);
    }
Esempio n. 7
0
    // --------------------------------------------------------------------------------------------

    #region Transformation

    public void SetPageTransform(XPageDirection direction, XPoint origion, XGraphicsUnit unit)
    {
      if (this.gfxStateStack.Count > 0)
        throw new InvalidOperationException("PageTransformation can be modified only when the graphics stack is empty.");

      throw new NotImplementedException("SetPageTransform");
    }
Esempio n. 8
0
 /// <summary>
 /// Transforms the specified point by this matrix and returns the result.
 /// </summary>
 public XPoint Transform(XPoint point)
 {
     double x = point.X;
     double y = point.Y;
     MultiplyPoint(ref x, ref y);
     return new XPoint(x, y);
 }
Esempio n. 9
0
    // --------------------------------------------------------------------------------------------

    #region Realizing graphical state

    /// <summary>
    /// Initializes the default view transformation, i.e. the transformation from the user page
    /// space to the PDF page space.
    /// </summary>
    void BeginPage()
    {
      if (this.gfxState.Level == GraphicsStackLevelInitial)
      {
        // Flip page horizontaly and mirror text.
        // TODO: Is PageOriging and PageScale (== Viewport) useful? Or just public DefaultViewMatrix (like Presentation Manager has had)
        this.defaultViewMatrix = new XMatrix();  //XMatrix.Identity;
        if (this.gfx.PageDirection == XPageDirection.Downwards)
        {
#if MIGRADOC
          if (this.pdflibHack)
          {
            // MigraDoc 1.1 (written in C++) based on PDFlib and our RenderContext for GDI+. To keep it running
            // on PDFlib (and PGL) I need this hack here in the MigraDoc build of PDFsharp.
            // The new and more flexible MigraDoc Rendering (written in C#) doesn't need it anymore.
            SaveState();
            defaultViewMatrix.Translate(0, this.page.Height);
            defaultViewMatrix.Scale(1, -1);
          }
          else
#endif
          {
            // Take TrimBox into account
            double pageHeight = Size.Height;
            XPoint trimOffset = new XPoint();
            if (this.page != null && this.page.TrimMargins.AreSet)
            {
              pageHeight += this.page.TrimMargins.Top.Point + this.page.TrimMargins.Bottom.Point;
              trimOffset = new XPoint(this.page.TrimMargins.Left.Point, this.page.TrimMargins.Top.Point);
            }

            if (this.page != null && this.page.Elements.GetInteger("/Rotate") == 90)  // HACK for InDesign flyer
            {
              defaultViewMatrix.RotatePrepend(90);
              defaultViewMatrix.ScalePrepend(1, -1);
            }
            else
            {
              // Recall that the value of Height depends on Orientation.
              defaultViewMatrix.TranslatePrepend(0, pageHeight);
              defaultViewMatrix.Scale(1, -1, XMatrixOrder.Prepend);
            }

            // Scale with page units
            switch (this.gfx.PageUnit)
            {
              case XGraphicsUnit.Inch:
                defaultViewMatrix.ScalePrepend(XUnit.InchFactor);
                break;

              case XGraphicsUnit.Millimeter:
                defaultViewMatrix.ScalePrepend(XUnit.MillimeterFactor);
                break;

              case XGraphicsUnit.Centimeter:
                defaultViewMatrix.ScalePrepend(XUnit.CentimeterFactor);
                break;
            }

            if (trimOffset != new XPoint())
            {
              Debug.Assert(this.gfx.PageUnit == XGraphicsUnit.Point, "With TrimMargins set the page units must be Point. Ohter cases nyi.");
              defaultViewMatrix.TranslatePrepend(trimOffset.x, trimOffset.y);
            }

            // Save initial graphic state
            SaveState();
            // Set page transformation
            double[] cm = defaultViewMatrix.GetElements();
            AppendFormat("{0:0.###} {1:0.###} {2:0.###} {3:0.###} {4:0.###} {5:0.###} cm ",
              cm[0], cm[1], cm[2], cm[3], cm[4], cm[5]);
            AppendFormat("-100 Tz\n");
          }
        }
        else
        {
          // Scale with page units
          switch (this.gfx.PageUnit)
          {
            case XGraphicsUnit.Inch:
              defaultViewMatrix.ScalePrepend(XUnit.InchFactor);
              break;

            case XGraphicsUnit.Millimeter:
              defaultViewMatrix.ScalePrepend(XUnit.MillimeterFactor);
              break;

            case XGraphicsUnit.Centimeter:
              defaultViewMatrix.ScalePrepend(XUnit.CentimeterFactor);
              break;
          }

          // Save initial graphic state
          SaveState();
          // Set page transformation
          double[] cm = defaultViewMatrix.GetElements();
          AppendFormat("{0:0.###} {1:0.###} {2:0.###} {3:0.###} {4:0.###} {5:0.###} cm ",
            cm[0], cm[1], cm[2], cm[3], cm[4], cm[5]);
        }
      }
    }
Esempio n. 10
0
        /// <summary>
        /// Parse a SVG path geometry string.
        /// </summary>
        /// <param name="context">The geometry context.</param>
        /// <param name="pathString">The path geometry string</param>
        /// <param name="startIndex">The string start index.</param>
        public void Parse(XGeometryContext context, string pathString, int startIndex)
        {
            _context         = context;
            _pathString      = pathString;
            _pathLength      = pathString.Length;
            _curIndex        = startIndex;
            _secondLastPoint = Point2.Create(0, 0);
            _lastPoint       = Point2.Create(0, 0);
            _lastStart       = Point2.Create(0, 0);
            _figureStarted   = false;
            bool first    = true;
            char last_cmd = ' ';

            while (ReadToken())
            {
                char cmd = _token;

                if (first)
                {
                    if ((cmd != 'M') && (cmd != 'm'))
                    {
                        InvalidToken();
                    }

                    first = false;
                }

                switch (cmd)
                {
                case 'm':
                case 'M':
                    _lastPoint = ReadPoint(cmd, !_allowComma);

                    _context.BeginFigure(XPoint.FromPoint2(_lastPoint), _isFilled, !_isClosed);
                    _figureStarted = true;
                    _lastStart     = _lastPoint;
                    last_cmd       = 'M';

                    while (IsNumber(_allowComma))
                    {
                        _lastPoint = ReadPoint(cmd, !_allowComma);
                        _context.LineTo(XPoint.FromPoint2(_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(XPoint.FromPoint2(_lastPoint), _isStroked, !_isSmoothJoin);
                    }while (IsNumber(_allowComma));

                    last_cmd = 'L';
                    break;

                case 'c':
                case 'C':
                case 's':
                case 'S':
                    EnsureFigure();

                    do
                    {
                        Point2 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.CubicBezierTo(
                            XPoint.FromPoint2(p),
                            XPoint.FromPoint2(_secondLastPoint),
                            XPoint.FromPoint2(_lastPoint),
                            _isStroked,
                            !_isSmoothJoin);

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

                    break;

                case 'q':
                case 'Q':
                case 't':
                case 'T':
                    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(
                            XPoint.FromPoint2(_secondLastPoint),
                            XPoint.FromPoint2(_lastPoint),
                            _isStroked,
                            !_isSmoothJoin);

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

                    break;

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

                    do
                    {
                        double w        = ReadNumber(!_allowComma);
                        double h        = ReadNumber(_allowComma);
                        double rotation = ReadNumber(_allowComma);
                        bool   large    = ReadBool();
                        bool   sweep    = ReadBool();

                        _lastPoint = ReadPoint(cmd, _allowComma);

                        _context.ArcTo(
                            XPoint.FromPoint2(_lastPoint),
                            XPathSize.Create(w, h),
                            rotation,
                            large,
                            sweep ? XSweepDirection.Clockwise : XSweepDirection.Counterclockwise,
                            _isStroked,
                            !_isSmoothJoin);
                    }while (IsNumber(_allowComma));

                    last_cmd = 'A';
                    break;

                case 'z':
                case 'Z':
                    EnsureFigure();
                    _context.SetClosedState(_isClosed);

                    _figureStarted = false;
                    last_cmd       = 'Z';
                    _lastPoint     = _lastStart;
                    break;

                default:
                    InvalidToken();
                    break;
                }
            }
        }
    /// <summary>
    /// Renders the bar code.
    /// </summary>
    protected internal override void Render(XGraphics gfx, XBrush brush, XFont font, XPoint position)
    {
      XGraphicsState state = gfx.Save();

      BarCodeRenderInfo info = new BarCodeRenderInfo(gfx, brush, font, position);
      InitRendering(info);
      info.CurrPosInString = 0;
      //info.CurrPos = info.Center - this.size / 2;
      info.CurrPos = position - CodeBase.CalcDistance(AnchorType.TopLeft, this.anchor, this.size);

      if (TurboBit)
        RenderTurboBit(info, true);
      RenderStart(info);
      while (info.CurrPosInString < this.text.Length)
      {
        RenderNextChar(info);
        RenderGap(info, false);
      }
      RenderStop(info);
      if (TurboBit)
        RenderTurboBit(info, false);
      if (TextLocation != TextLocation.None)
        RenderText(info);

      gfx.Restore(state);
    }
Esempio n. 12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="pg"></param>
        /// <param name="dx"></param>
        /// <param name="dy"></param>
        /// <param name="scale"></param>
        /// <returns></returns>
        public static XGraphicsPath ToXGraphicsPath(this PathGeometry pg, double dx, double dy, Func <double, double> scale)
        {
            var gp = new XGraphicsPath()
            {
                FillMode = pg.FillRule == FillRule.EvenOdd ? XFillMode.Alternate : XFillMode.Winding
            };

            foreach (var pf in pg.Figures)
            {
                var startPoint = pf.StartPoint;

                foreach (var segment in pf.Segments)
                {
                    if (segment is ArcSegment)
                    {
#if WPF
                        var arcSegment = segment as ArcSegment;
                        var point1     = new XPoint(
                            scale(startPoint.X + dx),
                            scale(startPoint.Y + dy));
                        var point2 = new XPoint(
                            scale(arcSegment.Point.X + dx),
                            scale(arcSegment.Point.Y + dy));
                        var size = new XSize(
                            scale(arcSegment.Size.Width),
                            scale(arcSegment.Size.Height));
                        gp.AddArc(
                            point1,
                            point2,
                            size, arcSegment.RotationAngle, arcSegment.IsLargeArc,
                            arcSegment.SweepDirection == SweepDirection.Clockwise ? XSweepDirection.Clockwise : XSweepDirection.Counterclockwise);
                        startPoint = arcSegment.Point;
#else
                        throw new NotSupportedException("Not supported segment type: " + segment.GetType());
                        //var arcSegment = segment as ArcSegment;
                        // TODO: Convert WPF/SVG elliptical arc segment format to GDI+ bezier curves.
                        //startPoint = arcSegment.Point;
#endif
                    }
                    else if (segment is CubicBezierSegment)
                    {
                        var cubicBezierSegment = segment as CubicBezierSegment;
                        gp.AddBezier(
                            scale(startPoint.X + dx),
                            scale(startPoint.Y + dy),
                            scale(cubicBezierSegment.Point1.X + dx),
                            scale(cubicBezierSegment.Point1.Y + dy),
                            scale(cubicBezierSegment.Point2.X + dx),
                            scale(cubicBezierSegment.Point2.Y + dy),
                            scale(cubicBezierSegment.Point3.X + dx),
                            scale(cubicBezierSegment.Point3.Y + dy));
                        startPoint = cubicBezierSegment.Point3;
                    }
                    else if (segment is LineSegment)
                    {
                        var lineSegment = segment as LineSegment;
                        gp.AddLine(
                            scale(startPoint.X + dx),
                            scale(startPoint.Y + dy),
                            scale(lineSegment.Point.X + dx),
                            scale(lineSegment.Point.Y + dy));
                        startPoint = lineSegment.Point;
                    }
                    else if (segment is PolyCubicBezierSegment)
                    {
                        var polyCubicBezierSegment = segment as PolyCubicBezierSegment;
                        if (polyCubicBezierSegment.Points.Length >= 3)
                        {
                            gp.AddBezier(
                                scale(startPoint.X + dx),
                                scale(startPoint.Y + dy),
                                scale(polyCubicBezierSegment.Points[0].X + dx),
                                scale(polyCubicBezierSegment.Points[0].Y + dy),
                                scale(polyCubicBezierSegment.Points[1].X + dx),
                                scale(polyCubicBezierSegment.Points[1].Y + dy),
                                scale(polyCubicBezierSegment.Points[2].X + dx),
                                scale(polyCubicBezierSegment.Points[2].Y + dy));
                        }

                        if (polyCubicBezierSegment.Points.Length > 3 &&
                            polyCubicBezierSegment.Points.Length % 3 == 0)
                        {
                            for (int i = 3; i < polyCubicBezierSegment.Points.Length; i += 3)
                            {
                                gp.AddBezier(
                                    scale(polyCubicBezierSegment.Points[i - 1].X + dx),
                                    scale(polyCubicBezierSegment.Points[i - 1].Y + dy),
                                    scale(polyCubicBezierSegment.Points[i].X + dx),
                                    scale(polyCubicBezierSegment.Points[i].Y + dy),
                                    scale(polyCubicBezierSegment.Points[i + 1].X + dx),
                                    scale(polyCubicBezierSegment.Points[i + 1].Y + dy),
                                    scale(polyCubicBezierSegment.Points[i + 2].X + dx),
                                    scale(polyCubicBezierSegment.Points[i + 2].Y + dy));
                            }
                        }

                        startPoint = polyCubicBezierSegment.Points.Last();
                    }
                    else if (segment is PolyLineSegment)
                    {
                        var polyLineSegment = segment as PolyLineSegment;
                        if (polyLineSegment.Points.Length >= 1)
                        {
                            gp.AddLine(
                                scale(startPoint.X + dx),
                                scale(startPoint.Y + dy),
                                scale(polyLineSegment.Points[0].X + dx),
                                scale(polyLineSegment.Points[0].Y + dy));
                        }

                        if (polyLineSegment.Points.Length > 1)
                        {
                            for (int i = 1; i < polyLineSegment.Points.Length; i++)
                            {
                                gp.AddLine(
                                    scale(polyLineSegment.Points[i - 1].X + dx),
                                    scale(polyLineSegment.Points[i - 1].Y + dy),
                                    scale(polyLineSegment.Points[i].X + dx),
                                    scale(polyLineSegment.Points[i].Y + dy));
                            }
                        }

                        startPoint = polyLineSegment.Points.Last();
                    }
                    else if (segment is PolyQuadraticBezierSegment)
                    {
                        var polyQuadraticSegment = segment as PolyQuadraticBezierSegment;
                        if (polyQuadraticSegment.Points.Length >= 2)
                        {
                            var    p1 = startPoint;
                            var    p2 = polyQuadraticSegment.Points[0];
                            var    p3 = polyQuadraticSegment.Points[1];
                            double x1 = p1.X;
                            double y1 = p1.Y;
                            double x2 = p1.X + (2.0 * (p2.X - p1.X)) / 3.0;
                            double y2 = p1.Y + (2.0 * (p2.Y - p1.Y)) / 3.0;
                            double x3 = x2 + (p3.X - p1.X) / 3.0;
                            double y3 = y2 + (p3.Y - p1.Y) / 3.0;
                            double x4 = p3.X;
                            double y4 = p3.Y;
                            gp.AddBezier(
                                scale(x1 + dx),
                                scale(y1 + dy),
                                scale(x2 + dx),
                                scale(y2 + dy),
                                scale(x3 + dx),
                                scale(y3 + dy),
                                scale(x4 + dx),
                                scale(y4 + dy));
                        }

                        if (polyQuadraticSegment.Points.Length > 2 &&
                            polyQuadraticSegment.Points.Length % 2 == 0)
                        {
                            for (int i = 3; i < polyQuadraticSegment.Points.Length; i += 3)
                            {
                                var    p1 = polyQuadraticSegment.Points[i - 1];
                                var    p2 = polyQuadraticSegment.Points[i];
                                var    p3 = polyQuadraticSegment.Points[i + 1];
                                double x1 = p1.X;
                                double y1 = p1.Y;
                                double x2 = p1.X + (2.0 * (p2.X - p1.X)) / 3.0;
                                double y2 = p1.Y + (2.0 * (p2.Y - p1.Y)) / 3.0;
                                double x3 = x2 + (p3.X - p1.X) / 3.0;
                                double y3 = y2 + (p3.Y - p1.Y) / 3.0;
                                double x4 = p3.X;
                                double y4 = p3.Y;
                                gp.AddBezier(
                                    scale(x1 + dx),
                                    scale(y1 + dy),
                                    scale(x2 + dx),
                                    scale(y2 + dy),
                                    scale(x3 + dx),
                                    scale(y3 + dy),
                                    scale(x4 + dx),
                                    scale(y4 + dy));
                            }
                        }

                        startPoint = polyQuadraticSegment.Points.Last();
                    }
                    else if (segment is QuadraticBezierSegment)
                    {
                        var    quadraticBezierSegment = segment as QuadraticBezierSegment;
                        var    p1 = startPoint;
                        var    p2 = quadraticBezierSegment.Point1;
                        var    p3 = quadraticBezierSegment.Point2;
                        double x1 = p1.X;
                        double y1 = p1.Y;
                        double x2 = p1.X + (2.0 * (p2.X - p1.X)) / 3.0;
                        double y2 = p1.Y + (2.0 * (p2.Y - p1.Y)) / 3.0;
                        double x3 = x2 + (p3.X - p1.X) / 3.0;
                        double y3 = y2 + (p3.Y - p1.Y) / 3.0;
                        double x4 = p3.X;
                        double y4 = p3.Y;
                        gp.AddBezier(
                            scale(x1 + dx),
                            scale(y1 + dy),
                            scale(x2 + dx),
                            scale(y2 + dy),
                            scale(x3 + dx),
                            scale(y3 + dy),
                            scale(x4 + dx),
                            scale(y4 + dy));
                        startPoint = quadraticBezierSegment.Point2;
                    }
                    else
                    {
                        throw new NotSupportedException("Not supported segment type: " + segment.GetType());
                    }
                }

                if (pf.IsClosed)
                {
                    gp.CloseFigure();
                }
                else
                {
                    gp.StartFigure();
                }
            }

            return(gp);
        }
 public static void AppHit(Effect effectData, EntityParent caster, List <long> effectTargetIDs, XPoint basePoint, bool isAddEffect)
 {
     for (int i = 0; i < effectTargetIDs.get_Count(); i++)
     {
         LocalBattleHitHandler.AppHit(effectData, caster, LocalAgent.GetEntityByID(effectTargetIDs.get_Item(i)), basePoint, isAddEffect);
     }
 }
Esempio n. 14
0
 /// <inheritdoc/>
 public override void BeginFigure(XPoint startPoint, bool isFilled = true, bool isClosed = true)
 {
     _currentFigure    = XPathFigure.Create(startPoint, isFilled, isClosed);
     _geometry.Figures = _geometry.Figures.Add(_currentFigure);
 }
Esempio n. 15
0
        /// <summary>
        /// Calculates the data label positions specific for pie charts.
        /// </summary>
        internal override void CalcPositions()
        {
            ChartRendererInfo cri = (ChartRendererInfo)_rendererParms.RendererInfo;
            XGraphics         gfx = _rendererParms.Graphics;

            if (cri.seriesRendererInfos.Length > 0)
            {
                SeriesRendererInfo sri = cri.seriesRendererInfos[0];
                if (sri != null && sri._dataLabelRendererInfo != null)
                {
                    int sectorIndex = 0;
                    foreach (SectorRendererInfo sector in sri._pointRendererInfos)
                    {
                        // Determine output rectangle
                        double midAngle    = sector.StartAngle + sector.SweepAngle / 2;
                        double radMidAngle = midAngle / 180 * Math.PI;
                        XPoint origin      = new XPoint(sector.Rect.X + sector.Rect.Width / 2,
                                                        sector.Rect.Y + sector.Rect.Height / 2);
                        double radius     = sector.Rect.Width / 2;
                        double halfradius = radius / 2;

                        DataLabelEntryRendererInfo dleri = sri._dataLabelRendererInfo.Entries[sectorIndex++];
                        switch (sri._dataLabelRendererInfo.Position)
                        {
                        case DataLabelPosition.OutsideEnd:
                            // Outer border of the circle.
                            dleri.X = origin.X + (radius * Math.Cos(radMidAngle));
                            dleri.Y = origin.Y + (radius * Math.Sin(radMidAngle));
                            if (dleri.X < origin.X)
                            {
                                dleri.X -= dleri.Width;
                            }
                            if (dleri.Y < origin.Y)
                            {
                                dleri.Y -= dleri.Height;
                            }
                            break;

                        case DataLabelPosition.InsideEnd:
                            // Inner border of the circle.
                            dleri.X = origin.X + (radius * Math.Cos(radMidAngle));
                            dleri.Y = origin.Y + (radius * Math.Sin(radMidAngle));
                            if (dleri.X > origin.X)
                            {
                                dleri.X -= dleri.Width;
                            }
                            if (dleri.Y > origin.Y)
                            {
                                dleri.Y -= dleri.Height;
                            }
                            break;

                        case DataLabelPosition.Center:
                            // Centered
                            dleri.X  = origin.X + (halfradius * Math.Cos(radMidAngle));
                            dleri.Y  = origin.Y + (halfradius * Math.Sin(radMidAngle));
                            dleri.X -= dleri.Width / 2;
                            dleri.Y -= dleri.Height / 2;
                            break;

                        case DataLabelPosition.InsideBase:
                            // Aligned at the base/center of the circle
                            dleri.X = origin.X;
                            dleri.Y = origin.Y;
                            if (dleri.X < origin.X)
                            {
                                dleri.X -= dleri.Width;
                            }
                            if (dleri.Y < origin.Y)
                            {
                                dleri.Y -= dleri.Height;
                            }
                            break;
                        }
                    }
                }
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Renders the content found in Text
        /// </summary>
        /// <param name="gfx">
        /// XGraphics - Instance of the drawing surface
        /// </param>
        /// <param name="brush">
        /// XBrush - Line and Color to draw the bar code
        /// </param>
        /// <param name="font">
        /// XFont - Font to use to draw the text string
        /// </param>
        /// <param name="position">
        /// XPoint - Location to render the bar code
        /// </param>
        protected internal override void Render(XGraphics gfx, XBrush brush, XFont font, XPoint position)
        {
            // Create the array to hold the values to be rendered
            this.Values = this.Code128Code == Code128Type.C ? new byte[this.text.Length / 2] : new byte[this.text.Length];
            String buffer = String.Empty;

            for (Int32 index = 0; index < text.Length; index++)
            {
                switch (this.Code128Code)
                {
                case Code128Type.A:
                    if (text[index] < 32)
                    {
                        this.Values[index] = (byte)(text[index] + 64);
                    }
                    else if ((text[index] >= 32) && (text[index] < 64))
                    {
                        this.Values[index] = (byte)(text[index] - 32);
                    }
                    else
                    {
                        this.Values[index] = (byte)text[index];
                    }
                    break;

                case Code128Type.B:
                    this.Values[index] = (byte)(text[index] - 32);
                    break;

                case Code128Type.C:
                    if ((text[index] >= '0') && (text[index] <= '9'))
                    {
                        buffer += text[index];
                        if (buffer.Length == 2)
                        {
                            this.Values[index / 2] = byte.Parse(buffer);
                            buffer = String.Empty;
                        }
                    }
                    else
                    {
                        throw new ArgumentOutOfRangeException("Parameter text (string) can only contain numeric characters for Code 128 - Code C");
                    }
                    break;
                }
            }
            if (this.Values == null)
            {
                throw new InvalidOperationException("Text or Values must be set");
            }
            if (this.Values.Length == 0)
            {
                throw new InvalidOperationException("Text or Values must have content");
            }
            for (int x = 0; x < this.Values.Length; x++)
            {
                if (this.Values[x] > 102)
                {
                    throw new ArgumentOutOfRangeException(BcgSR.InvalidCode128(x));
                }
            }
            XGraphicsState    state = gfx.Save();
            BarCodeRenderInfo info  = new BarCodeRenderInfo(gfx, brush, font, position);

            this.InitRendering(info);
            info.CurrPosInString = 0;
            info.CurrPos         = position - CodeBase.CalcDistance(AnchorType.TopLeft, this.anchor, this.size);
            this.RenderStart(info);
            foreach (byte c in this.Values)
            {
                this.RenderValue(info, c);
            }
            this.RenderStop(info);
            if (this.TextLocation != TextLocation.None)
            {
                this.RenderText(info);
            }
            gfx.Restore(state);
        }
Esempio n. 17
0
        void DumpPathData(PathData pathData)
        {
            XPoint[] points = new XPoint[pathData.Points.Length];
            for (int i = 0; i < points.Length; i++)
                points[i] = new XPoint(pathData.Points[i].X, pathData.Points[i].Y);

            DumpPathData(points, pathData.Types);
        }
Esempio n. 18
0
 /// <summary>
 /// Convert from WinForms point to core point.
 /// </summary>
 public static RPoint Convert(XPoint p)
 {
     return(new RPoint(p.X, p.Y));
 }
Esempio n. 19
0
        // ----- DrawPolygon --------------------------------------------------------------------------

        public void DrawPolygon(XPen pen, XBrush brush, XPoint[] points, XFillMode fillmode)
        {
            Realize(pen, brush);

            int count = points.Length;
            if (points.Length < 2)
                throw new ArgumentException("points", PSSR.PointArrayAtLeast(2));

            const string format = Config.SignificantFigures4;
            AppendFormatPoint("{0:" + format + "} {1:" + format + "} m\n", points[0].X, points[0].Y);
            for (int idx = 1; idx < count; idx++)
                AppendFormatPoint("{0:" + format + "} {1:" + format + "} l\n", points[idx].X, points[idx].Y);

            AppendStrokeFill(pen, brush, fillmode, true);
        }
Esempio n. 20
0
 /// <summary>
 /// Indicates whether the values are so close that they can be considered as equal.
 /// </summary>
 public static bool AreClose(XPoint point1, XPoint point2)
 {
     return(AreClose(point1.X, point2.X) && AreClose(point1.Y, point2.Y));
 }
Esempio n. 21
0
 /// <summary>
 /// Prepends a rotation of the specified angle at the specified point to this matrix.
 /// </summary>
 public void RotateAtPrepend(double angle, XPoint point)
 {
     RotateAt(angle, point, XMatrixOrder.Prepend);
 }
    public static void AppTheat(Effect effectData, EntityParent caster, List <long> effectTargetIDs, XPoint basePoint, int skillID, bool isAddEffect, bool isCommunicateMix)
    {
        if (!LocalAgent.GetEntityCalculatable(caster, isCommunicateMix))
        {
            return;
        }
        XDict <GameData.AttrType, long> effectCasterTempAttr = LocalBattleEffectCalculatorHandler.GetEffectCasterTempAttr(effectData, caster, skillID);
        bool flag = isAddEffect && isCommunicateMix;

        for (int i = 0; i < effectTargetIDs.get_Count(); i++)
        {
            EntityParent entityByID = LocalAgent.GetEntityByID(effectTargetIDs.get_Item(i));
            if (LocalAgent.GetEntityIsCurable(entityByID, isCommunicateMix))
            {
                if (!entityByID.IsUnconspicuous || effectData.forcePickup != 0)
                {
                    long num = BattleCalculator.CalculateTreatment(caster.BattleBaseAttrs, entityByID.BattleBaseAttrs, entityByID.IsEntitySelfType || entityByID.IsEntityPlayerType, effectCasterTempAttr, null);
                    if (num != 0L)
                    {
                        List <ClientDrvBuffInfo> casterBuffInfo = null;
                        List <ClientDrvBuffInfo> targetBuffInfo = null;
                        if (isCommunicateMix)
                        {
                            casterBuffInfo = LocalAgent.MakeClientDrvBuffInfo(caster.ID);
                            targetBuffInfo = LocalAgent.MakeClientDrvBuffInfo(effectTargetIDs.get_Item(i));
                        }
                        long num2 = LocalAgent.GetSpiritCurHp(entityByID, isCommunicateMix) + num;
                        if (num2 > entityByID.RealHpLmt)
                        {
                            num2 = entityByID.RealHpLmt;
                        }
                        Pos pos = null;
                        if (caster.Actor)
                        {
                            pos   = new Pos();
                            pos.x = caster.Actor.FixTransform.get_position().x * 100f;
                            pos.y = caster.Actor.FixTransform.get_position().z * 100f;
                        }
                        LocalAgent.SetSpiritCurHp(entityByID, num2, isCommunicateMix);
                        if (isCommunicateMix)
                        {
                            GlobalBattleNetwork.Instance.SendClientDriveBattleEffectDamage(caster.ID, effectTargetIDs.get_Item(i), caster.Hp, num2, num, skillID, effectData.id, flag, true, casterBuffInfo, targetBuffInfo, basePoint, new List <long>(), string.Concat(new object[]
                            {
                                caster.TryAddValue(GameData.AttrType.SkillTreatScaleBOAtk, effectCasterTempAttr),
                                "_",
                                caster.TryAddValue(GameData.AttrType.SkillTreatScaleBOHpLmt, effectCasterTempAttr),
                                "_",
                                caster.TryAddValue(GameData.AttrType.SkillIgnoreDefenceHurt, effectCasterTempAttr)
                            }), false);
                        }
                        LocalBattleProtocolSimulator.SendTreat(effectTargetIDs.get_Item(i), (GameObjectType.ENUM)entityByID.WrapType, caster.ID, (GameObjectType.ENUM)caster.WrapType, BattleAction_Treat.TreatSrcType.Treat, num, num2, pos);
                        if (flag)
                        {
                            flag = false;
                        }
                    }
                }
            }
        }
    }
Esempio n. 23
0
        /// <summary>
        /// Multiplies all points of the specified array with the this matrix.
        /// </summary>
        public void TransformPoints(XPoint[] points)
        {
            if (points == null)
                throw new ArgumentNullException("points");

            if (IsIdentity)
                return;

            int count = points.Length;
            for (int idx = 0; idx < count; idx++)
            {
                double x = points[idx].X;
                double y = points[idx].Y;
                points[idx].X = x * _m11 + y * _m21 + _offsetX;
                points[idx].Y = x * _m12 + y * _m22 + _offsetY;
            }
        }
Esempio n. 24
0
 /// <summary>
 /// Moving custom points
 /// </summary>
 /// <param name="point"></param>
 /// <param name="x"></param>
 /// <param name="y"></param>
 public void Move(ref XPoint point, int x, int y) => point = new XPoint((float)point.FormX + x, (float)point.FormY + y);
Esempio n. 25
0
    // ----- DrawLines ----------------------------------------------------------------------------

    /// <summary>
    /// Strokes a series of connected points.
    /// </summary>
    public void DrawLines(XPen pen, XPoint[] points)
    {
      if (pen == null)
        throw new ArgumentNullException("pen");
      if (points == null)
        throw new ArgumentNullException("points");

      int count = points.Length;
      if (count == 0)
        return;

      Realize(pen);

      AppendFormat("{0:0.###} {1:0.###} m\n", points[0].X, points[0].Y);
      for (int idx = 1; idx < count; idx++)
        AppendFormat("{0:0.###} {1:0.###} l\n", points[idx].X, points[idx].Y);
      this.content.Append("S\n");
    }
Esempio n. 26
0
        /// <summary>
        /// Draws the gridlines into the plot area.
        /// </summary>
        internal override void Draw()
        {
            ChartRendererInfo cri = (ChartRendererInfo)_rendererParms.RendererInfo;

            XRect plotAreaRect = cri.plotAreaRendererInfo.Rect;

            if (plotAreaRect.IsEmpty)
            {
                return;
            }

            AxisRendererInfo xari = cri.xAxisRendererInfo;
            AxisRendererInfo yari = cri.yAxisRendererInfo;

            double xMin          = xari.MinimumScale;
            double xMax          = xari.MaximumScale;
            double yMin          = yari.MinimumScale;
            double yMax          = yari.MaximumScale;
            double xMajorTick    = xari.MajorTick;
            double yMajorTick    = yari.MajorTick;
            double xMinorTick    = xari.MinorTick;
            double yMinorTick    = yari.MinorTick;
            double xMaxExtension = xari.MajorTick;

            XMatrix matrix = cri.plotAreaRendererInfo._matrix;

            LineFormatRenderer lineFormatRenderer;
            XGraphics          gfx = _rendererParms.Graphics;

            XPoint[] points = new XPoint[2];
            if (xari.MinorGridlinesLineFormat != null)
            {
                lineFormatRenderer = new LineFormatRenderer(gfx, xari.MinorGridlinesLineFormat);
                for (double x = xMin + xMinorTick; x < xMax; x += xMinorTick)
                {
                    points[0].Y = x;
                    points[0].X = yMin;
                    points[1].Y = x;
                    points[1].X = yMax;
                    matrix.TransformPoints(points);
                    lineFormatRenderer.DrawLine(points[0], points[1]);
                }
            }

            if (xari.MajorGridlinesLineFormat != null)
            {
                lineFormatRenderer = new LineFormatRenderer(gfx, xari.MajorGridlinesLineFormat);
                for (double x = xMin; x <= xMax; x += xMajorTick)
                {
                    points[0].Y = x;
                    points[0].X = yMin;
                    points[1].Y = x;
                    points[1].X = yMax;
                    matrix.TransformPoints(points);
                    lineFormatRenderer.DrawLine(points[0], points[1]);
                }
            }

            if (yari.MinorGridlinesLineFormat != null)
            {
                lineFormatRenderer = new LineFormatRenderer(gfx, yari.MinorGridlinesLineFormat);
                for (double y = yMin + yMinorTick; y < yMax; y += yMinorTick)
                {
                    points[0].Y = xMin;
                    points[0].X = y;
                    points[1].Y = xMax;
                    points[1].X = y;
                    matrix.TransformPoints(points);
                    lineFormatRenderer.DrawLine(points[0], points[1]);
                }
            }

            if (yari.MajorGridlinesLineFormat != null)
            {
                lineFormatRenderer = new LineFormatRenderer(gfx, yari.MajorGridlinesLineFormat);
                for (double y = yMin; y <= yMax; y += yMajorTick)
                {
                    points[0].Y = xMin;
                    points[0].X = y;
                    points[1].Y = xMax;
                    points[1].X = y;
                    matrix.TransformPoints(points);
                    lineFormatRenderer.DrawLine(points[0], points[1]);
                }
            }
        }
Esempio n. 27
0
    // ----- DrawClosedCurve ----------------------------------------------------------------------

    public void DrawClosedCurve(XPen pen, XBrush brush, XPoint[] points, double tension, XFillMode fillmode)
    {
      int count = points.Length;
      if (count == 0)
        return;
      if (count < 2)
        throw new ArgumentException("Not enough points", "points");

      // Simply tried out. Not proofed why it is correct.
      tension /= 3;

      Realize(pen, brush);

      AppendFormat("{0:0.####} {1:0.####} m\n", points[0].X, points[0].Y);
      if (count == 2)
      {
        // Just draws a line...
        AppendCurveSegment(points[0], points[0], points[1], points[1], tension);
      }
      else
      {
        AppendCurveSegment(points[count - 1], points[0], points[1], points[2], tension);
        for (int idx = 1; idx < count - 2; idx++)
          AppendCurveSegment(points[idx - 1], points[idx], points[idx + 1], points[idx + 2], tension);
        AppendCurveSegment(points[count - 3], points[count - 2], points[count - 1], points[0], tension);
        AppendCurveSegment(points[count - 2], points[count - 1], points[0], points[1], tension);
      }
      AppendStrokeFill(pen, brush, fillmode, true);
    }
Esempio n. 28
0
        /// <summary>
        /// Render a prepared page into a PDF document
        /// </summary>
        private Result <Nothing> OutputPage(PdfDocument document, DocumentPage pageToRender, XFont font, PageBacking background, int pageIndex, int pageTotal)
        {
            var pageDef = pageToRender.Definition;

            // If we have a source PDF, and we aren't trying to render a blank page, then import the page
            var shouldCopyPdfPage = background.ExistingPage != null && pageDef.RenderBackground;
            var page = shouldCopyPdfPage ? document.AddPage(background.ExistingPage !) : document.AddPage(/*blank*/);

            // If dimensions are silly, reset to A4
            if (pageDef.WidthMillimetres < 10 || pageDef.WidthMillimetres > 1000)
            {
                pageDef.WidthMillimetres = 210;
            }
            if (pageDef.HeightMillimetres < 10 || pageDef.HeightMillimetres > 1000)
            {
                pageDef.HeightMillimetres = 297;
            }

            // Set the PDF page size (in points under the hood)
            page.Width  = XUnit.FromMillimeter(pageDef.WidthMillimetres);
            page.Height = XUnit.FromMillimeter(pageDef.HeightMillimetres);

            using var gfx = XGraphics.FromPdfPage(page);
            gfx.Save();

            if (shouldCopyPdfPage && background.ExistingPage !.Rotate != 0)
            {
                // Match visual-rotations on page
                var centre       = new XPoint(0, 0);
                var visualRotate = background.ExistingPage !.Rotate % 360; // degrees, spec says it should be a multiple of 90.
                var angle        = 360.0 - visualRotate;
                gfx.RotateAtTransform(angle, centre);

                switch (visualRotate)
                {
                case 90:
                    gfx.TranslateTransform(-page.Height.Point, 0);
                    break;

                case 180:
                    gfx.TranslateTransform(-page.Width.Point, -page.Height.Point);
                    break;

                case 270:
                    gfx.TranslateTransform(-page.Height.Point / 2.0, -page.Height.Point);     // this one is a guess, as I don't have an example
                    break;

                default:
                    throw new Exception("Unhandled visual rotation case");
                }

                if (background.ExistingPage.Orientation == PageOrientation.Landscape)
                {
                    (page.Width, page.Height) = (page.Height, page.Width);
                }
            }

            // Draw background at full page size
            _loadingTimer.Start();
            if (pageDef.RenderBackground && background.BackgroundImage != null)
            {
                var destRect = new XRect(0, 0, (float)page.Width.Point, (float)page.Height.Point);
                gfx.DrawImage(background.BackgroundImage, destRect);
            }
            _loadingTimer.Stop();

            // Do default scaling
            var fx = page.Width.Point / page.Width.Millimeter;
            var fy = page.Height.Point / page.Height.Millimeter;

            // If using an image, work out the bitmap -> page adjustment
            if (background.BackgroundImage != null)
            {
                fx = page.Width.Point / background.BackgroundImage.PixelWidth;
                fy = page.Height.Point / background.BackgroundImage.PixelHeight;
            }

            // Draw each box.
            foreach (var boxDef in pageToRender.DocumentBoxes)
            {
                var result = RenderBox(font, boxDef, fx, fy, gfx, pageToRender, pageIndex, pageTotal);
                if (result.IsFailure)
                {
                    return(result);
                }
            }

            gfx.Restore();

            return(Result.Success());
        }
Esempio n. 29
0
 /// <summary>
 /// Renders the content found in Text
 /// </summary>
 /// <param name="gfx">
 /// XGraphics - Instance of the drawing surface 
 /// </param>
 /// <param name="brush">
 /// XBrush - Line and Color to draw the bar code 
 /// </param>
 /// <param name="font">
 /// XFont - Font to use to draw the text string 
 /// </param>
 /// <param name="position">
 /// XPoint - Location to render the bar code 
 /// </param>
 protected internal override void Render(XGraphics gfx, XBrush brush, XFont font, XPoint position)
 {
     // Create the array to hold the values to be rendered
     this.Values = this.Code128Code == Code128Type.C ? new byte[this.text.Length / 2] : new byte[this.text.Length];
     String buffer = String.Empty;
     for (Int32 index = 0; index < text.Length; index++)
         switch (this.Code128Code)
         {
             case Code128Type.A:
                 if (text[index] < 32)
                     this.Values[index] = (byte)(text[index] + 64);
                 else if ((text[index] >= 32) && (text[index] < 64))
                     this.Values[index] = (byte)(text[index] - 32);
                 else
                     this.Values[index] = (byte)text[index];
                 break;
             case Code128Type.B:
                 this.Values[index] = (byte)(text[index] - 32);
                 break;
             case Code128Type.C:
                 if ((text[index] >= '0') && (text[index] <= '9'))
                 {
                     buffer += text[index];
                     if (buffer.Length == 2)
                     {
                         this.Values[index / 2] = byte.Parse(buffer);
                         buffer = String.Empty;
                     }
                 }
                 else
                     throw new ArgumentOutOfRangeException("Parameter text (string) can only contain numeric characters for Code 128 - Code C");
                 break;
         }
     if (this.Values == null)
         throw new InvalidOperationException("Text or Values must be set");
     if (this.Values.Length == 0)
         throw new InvalidOperationException("Text or Values must have content");
     for (int x = 0; x < this.Values.Length; x++)
         if (this.Values[x] > 102)
             throw new ArgumentOutOfRangeException(BcgSR.InvalidCode128(x));
     XGraphicsState state = gfx.Save();
     BarCodeRenderInfo info = new BarCodeRenderInfo(gfx, brush, font, position);
     this.InitRendering(info);
     info.CurrPosInString = 0;
     info.CurrPos = position - CodeBase.CalcDistance(AnchorType.TopLeft, this.anchor, this.size);
     this.RenderStart(info);
     foreach (byte c in this.Values)
         this.RenderValue(info, c);
     this.RenderStop(info);
     if (this.TextLocation != TextLocation.None)
         this.RenderText(info);
     gfx.Restore(state);
 }
Esempio n. 30
0
        /// <summary>
        /// Renders the bar code.
        /// </summary>
        protected internal override void Render(XGraphics gfx, XBrush brush, XFont font, XPoint position)
        {
            XGraphicsState state = gfx.Save();

            BarCodeRenderInfo info = new BarCodeRenderInfo(gfx, brush, font, position);

            InitRendering(info);
            info.CurrPosInString = 0;
            //info.CurrPos = info.Center - Size / 2;
            info.CurrPos = position - CodeBase.CalcDistance(AnchorType.TopLeft, Anchor, Size);

            if (TurboBit)
            {
                RenderTurboBit(info, true);
            }
            RenderStart(info);
            while (info.CurrPosInString < Text.Length)
            {
                RenderNextPair(info);
            }
            RenderStop(info);
            if (TurboBit)
            {
                RenderTurboBit(info, false);
            }
            if (TextLocation != TextLocation.None)
            {
                RenderText(info);
            }

            gfx.Restore(state);
        }
        /// <summary>
        /// Calculate angles for each sector.
        /// </summary>
        protected override void CalcSectors()
        {
            ChartRendererInfo cri = (ChartRendererInfo)this.rendererParms.RendererInfo;

            if (cri.seriesRendererInfos.Length == 0)
            {
                return;
            }

            SeriesRendererInfo sri = cri.seriesRendererInfos[0];

            double sumValues = sri.SumOfPoints;

            if (sumValues == 0)
            {
                return;
            }

            double textMeasure = 0;

            if (sri.dataLabelRendererInfo != null && sri.dataLabelRendererInfo.Position == DataLabelPosition.OutsideEnd)
            {
                foreach (DataLabelEntryRendererInfo dleri in sri.dataLabelRendererInfo.Entries)
                {
                    textMeasure = Math.Max(textMeasure, dleri.Width);
                    textMeasure = Math.Max(textMeasure, dleri.Height);
                }
            }

            XRect pieRect = cri.plotAreaRendererInfo.Rect;

            if (textMeasure != 0)
            {
                pieRect.X      += textMeasure;
                pieRect.Y      += textMeasure;
                pieRect.Width  -= 2 * textMeasure;
                pieRect.Height -= 2 * textMeasure;
            }

            XPoint origin    = new XPoint(pieRect.X + pieRect.Width / 2, pieRect.Y + pieRect.Height / 2);
            XRect  innerRect = new XRect();
            XPoint p1        = new XPoint();

            double midAngle = 0, sectorStartAngle = 0, sectorSweepAngle = 0,
                   deltaAngle = 2, startAngle = 270, sweepAngle = 0,
                   rInnerCircle = pieRect.Width / 15,
                   rOuterCircle = pieRect.Width / 2;

            foreach (SectorRendererInfo sector in sri.pointRendererInfos)
            {
                if (!double.IsNaN(sector.point.value) && sector.point.value != 0)
                {
                    sweepAngle = 360 / (sumValues / Math.Abs(sector.point.value));

                    midAngle         = startAngle + sweepAngle / 2;
                    sectorStartAngle = Math.Max(0, startAngle + deltaAngle);
                    sectorSweepAngle = Math.Max(sweepAngle, sweepAngle - deltaAngle);

                    p1.X             = origin.X + rInnerCircle * Math.Cos(midAngle / 180 * Math.PI);
                    p1.Y             = origin.Y + rInnerCircle * Math.Sin(midAngle / 180 * Math.PI);
                    innerRect.X      = p1.X - rOuterCircle + rInnerCircle;
                    innerRect.Y      = p1.Y - rOuterCircle + rInnerCircle;
                    innerRect.Width  = (rOuterCircle - rInnerCircle) * 2;
                    innerRect.Height = innerRect.Width;

                    sector.Rect       = innerRect;
                    sector.StartAngle = sectorStartAngle;
                    sector.SweepAngle = sectorSweepAngle;

                    startAngle += sweepAngle;
                }
                else
                {
                    sector.StartAngle = double.NaN;
                    sector.SweepAngle = double.NaN;
                }
            }
        }
Esempio n. 32
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="img"></param>
        /// <param name="path"></param>
        /// <param name="exportItem"></param>
        /// <returns>byte[]</returns>
        private byte[] createPdf(Image img, MapExportItem exportItem, string fontName)
        {
            PdfDocument document = new PdfDocument();
            PdfPage     page     = document.AddPage();

            page.Size        = GetPageSize(exportItem);
            page.Orientation = exportItem.orientation == "L" ? PdfSharp.PageOrientation.Landscape : PdfSharp.PageOrientation.Portrait;

            XGraphics gfx = XGraphics.FromPdfPage(page);

            int    scale      = int.Parse(exportItem.scale);
            double length     = (1.0 / scale);
            double unitLength = (length * 2.82e3);

            Dictionary <int, string> scaleBarTexts = new Dictionary <int, string>()
            {
                { 250, "25 m" },
                { 500, "50 m" },
                { 1000, "50 m" },
                { 2500, "100 m" },
                { 5000, "200 m" },
                { 10000, "500 m" },
                { 25000, "1 km" },
                { 50000, "2 km" },
                { 100000, "5 km" },
                { 250000, "10 km" }
            };

            Dictionary <int, int> scaleBarLengths = new Dictionary <int, int>()
            {
                { 250, 25 },
                { 500, 50 },
                { 1000, 50 },
                { 2500, 100 },
                { 5000, 200 },
                { 10000, 500 },
                { 25000, 1000 },
                { 50000, 2000 },
                { 100000, 5000 },
                { 250000, 10000 }
            };

            int    displayLength = GetDisplayLength(unitLength, scaleBarLengths, scale);
            string displayText   = GetDisplayText(unitLength, scaleBarTexts, scale);

            // adding support for different layouts
            int layout = ConfigurationManager.AppSettings["exportLayout"] != null?int.Parse(ConfigurationManager.AppSettings["exportLayout"]) : 1;

            if (layout == 1)//original layout
            {
                //origina code from github

                this.drawImage(gfx, img, 0, 0, page);

                List <string> copyrights = new List <string>();
                if (ConfigurationManager.AppSettings["exportCopyrightText"] != null)
                {
                    copyrights = ConfigurationManager.AppSettings["exportCopyrightText"].Split(',').ToList();
                }

                string infoText = String.Empty;
                if (ConfigurationManager.AppSettings["exportInfoText"] != null)
                {
                    infoText = ConfigurationManager.AppSettings["exportInfoText"];
                }

                int height = 45 + copyrights.Count * 10;

                XPoint[] points = new XPoint[]
                {
                    new XPoint(12, 12),
                    new XPoint(12, height),
                    new XPoint(55 + displayLength, height),
                    new XPoint(55 + displayLength, 12),
                    new XPoint(12, 12)
                };

                gfx.DrawPolygon(XBrushes.White, points, XFillMode.Winding);

                this.drawText(gfx, fontName, String.Format("Skala 1:{0}", exportItem.scale), 15, 25);
                gfx.DrawLine(XPens.Black, new XPoint(15, 32), new XPoint(15 + displayLength, 32));
                gfx.DrawLine(XPens.Black, new XPoint(15, 28), new XPoint(15, 36));
                gfx.DrawLine(XPens.Black, new XPoint(15 + displayLength, 28), new XPoint(15 + displayLength, 36));
                this.drawText(gfx, fontName, displayText, 20 + displayLength, 35);

                var y = (int)page.Height.Point - 15;

                this.drawText(gfx, fontName, infoText, 15, y);

                int i = 0;
                copyrights.ForEach(copyright =>
                {
                    int start = 50;
                    this.drawText(gfx, fontName, String.Format("© {0}", copyright), 15, start + i * 10);
                    i++;
                });

                XImage logo = XImage.FromFile(Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "assets", "logo.png"));
                gfx.DrawImage(logo, (gfx.PageSize.Width - logo.PixelWidth / 2) - 12, 12, logo.PixelWidth / 2, logo.PixelHeight / 2);

                byte[] bytes;

                using (MemoryStream ms = new MemoryStream())
                {
                    document.Save(ms);
                    bytes = ReadFully(ms);
                }

                return(bytes);
            }
            else if (layout == 2)//new layout
            {
                // x and y 0 0(top left corner?)-> change
                this.drawImage(gfx, img, 33, 33, page);

                List <string> copyrights = new List <string>();
                if (ConfigurationManager.AppSettings["exportCopyrightText"] != null)
                {
                    copyrights = ConfigurationManager.AppSettings["exportCopyrightText"].Split(',').ToList();
                }

                string infoText = String.Empty;
                if (ConfigurationManager.AppSettings["exportInfoText"] != null)
                {
                    infoText = ConfigurationManager.AppSettings["exportInfoText"];
                }

                int height = 1;

                XPoint[] points = new XPoint[]
                {
                    new XPoint(12, 12),
                    new XPoint(12, height),
                    new XPoint(55 + displayLength, height),
                    new XPoint(55 + displayLength, 12),
                    new XPoint(12, 12)
                };

                gfx.DrawPolygon(XBrushes.White, points, XFillMode.Winding);
                // x y
                this.drawText(gfx, fontName, String.Format("Skala 1:{0}", exportItem.scale), 33, (int)page.Height.Point - 23, 8);
                gfx.DrawLine(XPens.Black, new XPoint(33, (int)page.Height.Point - 18), new XPoint(33 + displayLength, (int)page.Height.Point - 18));
                gfx.DrawLine(XPens.Black, new XPoint(33, (int)page.Height.Point - 15), new XPoint(33, (int)page.Height.Point - 21));
                gfx.DrawLine(XPens.Black, new XPoint(33 + displayLength / 2, (int)page.Height.Point - 17), new XPoint(33 + displayLength / 2, (int)page.Height.Point - 19));
                gfx.DrawLine(XPens.Black, new XPoint(33 + displayLength, (int)page.Height.Point - 15), new XPoint(33 + displayLength, (int)page.Height.Point - 21));
                this.drawText(gfx, fontName, displayText, 38 + displayLength, (int)page.Height.Point - 16, 8);

                var y = (int)page.Height.Point - 2;

                this.drawText(gfx, fontName, infoText, 33, y, 8);

                int i = 0;
                copyrights.ForEach(copyright =>
                {
                    int start = (int)page.Height.Point - 15;
                    this.drawText(gfx, fontName, String.Format("© {0}", copyright), (int)page.Width.Point - 100, start + i * 10, 8);
                    i++;
                });

                XImage logo = XImage.FromFile(Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "assets", "logo.png"));
                gfx.DrawImage(logo, (gfx.PageSize.Width - logo.PixelWidth / 5) - 33, 3.5, logo.PixelWidth / 5, logo.PixelHeight / 5);

                byte[] bytes;

                using (MemoryStream ms = new MemoryStream())
                {
                    document.Save(ms);
                    bytes = ReadFully(ms);
                }

                return(bytes);
            }
            else if (layout == 3)
            {
                List <string> copyrights = new List <string>();
                if (ConfigurationManager.AppSettings["exportCopyrightText"] != null)
                {
                    copyrights = ConfigurationManager.AppSettings["exportCopyrightText"].Split(',').ToList();
                }

                string infoText = String.Empty;
                if (ConfigurationManager.AppSettings["exportInfoText"] != null)
                {
                    infoText = ConfigurationManager.AppSettings["exportInfoText"];
                }

                // Get logoimage
                XImage logo = XImage.FromFile(Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "assets", "logo.png"));

                // Set positions, areas, brushes and pens
                XRect margins   = new XRect(33, 33, 33, 33);
                XSize stampSize = new XSize(200, 120);

                // Calculate positions and areas
                XRect  drawingArea        = new XRect(margins.Left, margins.Top, page.Width - (margins.Left + margins.Width), page.Height - (margins.Top + margins.Height));
                XRect  stampArea          = new XRect(new XPoint(drawingArea.Left + 15, drawingArea.Bottom - stampSize.Height - 15), stampSize);
                XRect  logoArea           = new XRect(new XPoint(stampArea.Left + 10, stampArea.Top + 10), new XPoint(stampArea.Right - 10, stampArea.Top + 50));
                XPoint signingLine        = new XPoint(stampArea.Left + 10, logoArea.Bottom + 30);
                XPoint copyrightPosition  = new XPoint(drawingArea.Right - 3, drawingArea.Bottom - 3);
                XPoint scalLegendPosition = new XPoint(stampArea.Left + 10, signingLine.Y + 20);

                double scaling;
                var    scalingY = logo.PointHeight / logoArea.Height;
                var    scalingX = logo.PointWidth / logoArea.Width;
                if (scalingX < scalingY)
                {
                    scaling = scalingX;
                }
                else
                {
                    scaling = scalingY;
                }

                // Pens, Brushes and colors
                XColor mainColor = XColor.FromArgb(0, 119, 188);
                XPen   thickPen  = new XPen(mainColor, 1);
                XPen   thinPen   = new XPen(mainColor, 0.5);

                // Draw map
                this.drawImage(gfx, img, drawingArea.Left, drawingArea.Top, page);

                // Put a border around map
                gfx.DrawRectangle(thickPen, drawingArea);

                // Draw a white "stamparea"
                gfx.DrawRectangle(thickPen, XBrushes.White, stampArea);
                // Draw logo
                gfx.DrawImage(logo, logoArea.Left, logoArea.Top, logo.PointWidth / scaling, logo.PointHeight / scaling);
                // Draw "signing line"

                gfx.DrawLine(thinPen, signingLine, new XPoint(stampArea.Right - 10, signingLine.Y));

                // Draw scale legend
                gfx.DrawLine(XPens.Black, new XPoint(scalLegendPosition.X, scalLegendPosition.Y), new XPoint(scalLegendPosition.X + displayLength, scalLegendPosition.Y));
                gfx.DrawLine(XPens.Black, new XPoint(scalLegendPosition.X, scalLegendPosition.Y - 3), new XPoint(scalLegendPosition.X, scalLegendPosition.Y + 3));
                gfx.DrawLine(XPens.Black, new XPoint(scalLegendPosition.X + displayLength / 2, scalLegendPosition.Y - 2), new XPoint(scalLegendPosition.X + displayLength / 2, scalLegendPosition.Y + 2));
                gfx.DrawLine(XPens.Black, new XPoint(scalLegendPosition.X + displayLength, scalLegendPosition.Y - 3), new XPoint(scalLegendPosition.X + displayLength, scalLegendPosition.Y + 3));
                XFont font = new XFont(fontName, 6);
                gfx.DrawString(String.Format("Skala 1:{0}", exportItem.scale), font, XBrushes.Black, new XRect(new XPoint(scalLegendPosition.X, scalLegendPosition.Y - 12), new XPoint(scalLegendPosition.X + displayLength, scalLegendPosition.Y - 2)), XStringFormats.TopLeft);
                gfx.DrawString(displayText, font, XBrushes.Black, (int)scalLegendPosition.X + displayLength + 10, (int)scalLegendPosition.Y + 2);

                // Draw infotext
                this.drawText(gfx, fontName, infoText, (int)stampArea.Left + 10, (int)stampArea.Bottom - 5, 5);

                // Draw copyright notes
                int i = 0;
                copyrights.ForEach(copyright =>
                {
                    if (i > 0)
                    {
                        copyrightPosition.Offset(0, -10);
                    }
                    gfx.DrawString(String.Format("© {0}", copyright), font, XBrushes.Black, copyrightPosition, XStringFormats.BottomRight);

                    i++;
                });


                byte[] bytes;

                using (MemoryStream ms = new MemoryStream())
                {
                    document.Save(ms);
                    bytes = ReadFully(ms);
                }

                return(bytes);
            }

            return(null);
        }
Esempio n. 33
0
        /// <summary>
        /// Convert a point from Windows world space to PDF world space.
        /// </summary>
        internal XPoint WorldToView(XPoint point)
        {
            // If EffectiveCtm is not yet realized InverseEffectiveCtm is invalid.
            Debug.Assert(_gfxState.UnrealizedCtm.IsIdentity, "Somewhere a RealizeTransform is missing.");
#if true
            // See in #else case why this is correct.
            XPoint pt = _gfxState.WorldTransform.Transform(point);
            return _gfxState.InverseEffectiveCtm.Transform(new XPoint(pt.X, PageHeightPt / DefaultViewMatrix.M22 - pt.Y));
#else
            // Get inverted PDF world transform matrix.
            XMatrix invers = _gfxState.EffectiveCtm;
            invers.Invert();

            // Apply transform in Windows world space.
            XPoint pt1 = _gfxState.WorldTransform.Transform(point);
#if true
            // Do the transformation (see #else case) in one step.
            XPoint pt2 = new XPoint(pt1.X, PageHeightPt / DefaultViewMatrix.M22 - pt1.Y);
#else
            // Replicable version

            // Apply default transformation.
            pt1.X = pt1.X * DefaultViewMatrix.M11;
            pt1.Y = pt1.Y * DefaultViewMatrix.M22;

            // Convert from Windows space to PDF space.
            XPoint pt2 = new XPoint(pt1.X, PageHeightPt - pt1.Y);

            pt2.X = pt2.X / DefaultViewMatrix.M11;
            pt2.Y = pt2.Y / DefaultViewMatrix.M22;
#endif
            XPoint pt3 = invers.Transform(pt2);
            return pt3;
#endif
        }
        /// <summary>
        /// Calculates the position, width and height of each bar of all series.
        /// </summary>
        protected override void CalcBars()
        {
            ChartRendererInfo cri = (ChartRendererInfo)_rendererParms.RendererInfo;

            if (cri.seriesRendererInfos.Length == 0)
            {
                return;
            }

            double xMax = cri.xAxisRendererInfo.MaximumScale;
            double yMin = cri.yAxisRendererInfo.MinimumScale;
            double yMax = cri.yAxisRendererInfo.MaximumScale;

            int pointCount = 0;

            foreach (SeriesRendererInfo sri in cri.seriesRendererInfos)
            {
                pointCount += sri._series._seriesElements.Count;
            }

            // Space shared by one clustered bar.
            double groupWidth = cri.xAxisRendererInfo.MajorTick;

            // Space used by one bar.
            double columnWidth = groupWidth * 0.75 / cri.seriesRendererInfos.Length;

            int seriesIdx = 0;

            XPoint[] points = new XPoint[2];
            foreach (SeriesRendererInfo sri in cri.seriesRendererInfos)
            {
                // Set x to first clustered bar for each series.
                double x = xMax - groupWidth / 2;

                // Offset for bars of a particular series from the start of a clustered bar.
                double dx = (columnWidth * seriesIdx) - (columnWidth / 2 * cri.seriesRendererInfos.Length);
                double y0 = yMin;

                foreach (ColumnRendererInfo column in sri._pointRendererInfos)
                {
                    if (column.Point != null)
                    {
                        double x0 = x - dx;
                        double x1 = x - dx - columnWidth;
                        double y1 = column.Point.Value;

                        // Draw from zero base line, if it exists.
                        if (y0 < 0 && yMax >= 0)
                        {
                            y0 = 0;
                        }

                        // y0 should always be lower than y1, i. e. draw bar from bottom to top.
                        if (y1 < 0 && y1 < y0)
                        {
                            double y = y0;
                            y0 = y1;
                            y1 = y;
                        }

                        points[0].X = y0; // upper left
                        points[0].Y = x0;
                        points[1].X = y1; // lower right
                        points[1].Y = x1;

                        cri.plotAreaRendererInfo._matrix.TransformPoints(points);

                        column.Rect = new XRect(points[0].X,
                                                points[1].Y,
                                                points[1].X - points[0].X,
                                                points[0].Y - points[1].Y);
                    }
                    x--; // Next clustered bar.
                }
                seriesIdx++;
            }
        }
Esempio n. 35
0
 void DumpPathData(XPoint[] points, byte[] types)
 {
     int count = points.Length;
     for (int idx = 0; idx < count; idx++)
     {
         string info = PdfEncoders.Format("{0:X}   {1:####0.000} {2:####0.000}", types[idx], points[idx].X, points[idx].Y);
         Debug.WriteLine(info, "PathData");
     }
 }
        /// <summary>
        /// Draws the horizontal X axis.
        /// </summary>
        internal override void Draw()
        {
            XGraphics         gfx  = _rendererParms.Graphics;
            ChartRendererInfo cri  = (ChartRendererInfo)_rendererParms.RendererInfo;
            AxisRendererInfo  xari = cri.xAxisRendererInfo;

            double xMin          = xari.MinimumScale;
            double xMax          = xari.MaximumScale;
            double xMajorTick    = xari.MajorTick;
            double xMinorTick    = xari.MinorTick;
            double xMaxExtension = xari.MajorTick;

            // Draw tick labels. Each tick label will be aligned centered.
            int    countTickLabels = (int)xMax;
            double tickLabelStep   = xari.Width;

            if (countTickLabels != 0)
            {
                tickLabelStep = xari.Width / countTickLabels;
            }

            //XPoint startPos = new XPoint(xari.X + tickLabelStep / 2, xari.Y + /*xari.TickLabelsHeight +*/ xari.MajorTickMarkWidth);
            XPoint startPos = new XPoint(xari.X + tickLabelStep / 2, xari.Y + xari.TickLabelsHeight);

            if (xari.MajorTickMark != TickMarkType.None)
            {
                startPos.Y += xari.MajorTickMarkWidth;
            }
            foreach (XSeries xs in xari.XValues)
            {
                for (int idx = 0; idx < countTickLabels && idx < xs.Count; ++idx)
                {
                    XValue xv = xs[idx];
                    if (xv != null)
                    {
                        string tickLabel = xv._value;
                        XSize  size      = gfx.MeasureString(tickLabel, xari.TickLabelsFont);
                        gfx.DrawString(tickLabel, xari.TickLabelsFont, xari.TickLabelsBrush, startPos.X - size.Width / 2, startPos.Y);
                    }
                    startPos.X += tickLabelStep;
                }
            }

            // Draw axis.
            // First draw tick marks, second draw axis.
            double majorTickMarkStart = 0, majorTickMarkEnd = 0,
                   minorTickMarkStart = 0, minorTickMarkEnd = 0;

            GetTickMarkPos(xari, ref majorTickMarkStart, ref majorTickMarkEnd, ref minorTickMarkStart, ref minorTickMarkEnd);

            LineFormatRenderer lineFormatRenderer = new LineFormatRenderer(gfx, xari.LineFormat);

            XPoint[] points = new XPoint[2];

            // Minor ticks.
            if (xari.MinorTickMark != TickMarkType.None)
            {
                int    countMinorTickMarks = (int)(xMax / xMinorTick);
                double minorTickMarkStep   = xari.Width / countMinorTickMarks;
                startPos.X = xari.X;
                for (int x = 0; x <= countMinorTickMarks; x++)
                {
                    points[0].X = startPos.X + minorTickMarkStep * x;
                    points[0].Y = minorTickMarkStart;
                    points[1].X = points[0].X;
                    points[1].Y = minorTickMarkEnd;
                    lineFormatRenderer.DrawLine(points[0], points[1]);
                }
            }

            // Major ticks.
            if (xari.MajorTickMark != TickMarkType.None)
            {
                int    countMajorTickMarks = (int)(xMax / xMajorTick);
                double majorTickMarkStep   = xari.Width;
                if (countMajorTickMarks != 0)
                {
                    majorTickMarkStep = xari.Width / countMajorTickMarks;
                }
                startPos.X = xari.X;
                for (int x = 0; x <= countMajorTickMarks; x++)
                {
                    points[0].X = startPos.X + majorTickMarkStep * x;
                    points[0].Y = majorTickMarkStart;
                    points[1].X = points[0].X;
                    points[1].Y = majorTickMarkEnd;
                    lineFormatRenderer.DrawLine(points[0], points[1]);
                }
            }

            // Axis.
            if (xari.LineFormat != null)
            {
                points[0].X = xari.X;
                points[0].Y = xari.Y;
                points[1].X = xari.X + xari.Width;
                points[1].Y = xari.Y;
                if (xari.MajorTickMark != TickMarkType.None)
                {
                    points[0].X -= xari.LineFormat.Width / 2;
                    points[1].X += xari.LineFormat.Width / 2;
                }
                lineFormatRenderer.DrawLine(points[0], points[1]);
            }

            // Draw axis title.
            AxisTitleRendererInfo atri = xari._axisTitleRendererInfo;

            if (atri != null && atri.AxisTitleText != null && atri.AxisTitleText.Length > 0)
            {
                XRect rect = new XRect(xari.Rect.Right / 2 - atri.AxisTitleSize.Width / 2, xari.Rect.Bottom,
                                       atri.AxisTitleSize.Width, 0);
                gfx.DrawString(atri.AxisTitleText, atri.AxisTitleFont, atri.AxisTitleBrush, rect);
            }
        }
Esempio n. 37
0
        // ----- DrawString ---------------------------------------------------------------------------

        public void DrawString(string s, XFont font, XBrush brush, XRect rect, XStringFormat format)
        {
            double x = rect.X;
            double y = rect.Y;

            double lineSpace = font.GetHeight();
            double cyAscent = lineSpace * font.CellAscent / font.CellSpace;
            double cyDescent = lineSpace * font.CellDescent / font.CellSpace;
            double width = _gfx.MeasureString(s, font).Width;

            //bool bold = (font.Style & XFontStyle.Bold) != 0;
            //bool italic = (font.Style & XFontStyle.Italic) != 0;
            bool italicSimulation = (font.GlyphTypeface.StyleSimulations & XStyleSimulations.ItalicSimulation) != 0;
            bool boldSimulation = (font.GlyphTypeface.StyleSimulations & XStyleSimulations.BoldSimulation) != 0;
            bool strikeout = (font.Style & XFontStyle.Strikeout) != 0;
            bool underline = (font.Style & XFontStyle.Underline) != 0;

            Realize(font, brush, boldSimulation ? 2 : 0);

            switch (format.Alignment)
            {
                case XStringAlignment.Near:
                    // nothing to do
                    break;

                case XStringAlignment.Center:
                    x += (rect.Width - width) / 2;
                    break;

                case XStringAlignment.Far:
                    x += rect.Width - width;
                    break;
            }
            if (Gfx.PageDirection == XPageDirection.Downwards)
            {
                switch (format.LineAlignment)
                {
                    case XLineAlignment.Near:
                        y += cyAscent;
                        break;

                    case XLineAlignment.Center:
                        // TODO: Use CapHeight. PDFlib also uses 3/4 of ascent
                        y += (cyAscent * 3 / 4) / 2 + rect.Height / 2;
                        break;

                    case XLineAlignment.Far:
                        y += -cyDescent + rect.Height;
                        break;

                    case XLineAlignment.BaseLine:
                        // Nothing to do.
                        break;
                }
            }
            else
            {
                switch (format.LineAlignment)
                {
                    case XLineAlignment.Near:
                        y += cyDescent;
                        break;

                    case XLineAlignment.Center:
                        // TODO: Use CapHeight. PDFlib also uses 3/4 of ascent
                        y += -(cyAscent * 3 / 4) / 2 + rect.Height / 2;
                        break;

                    case XLineAlignment.Far:
                        y += -cyAscent + rect.Height;
                        break;

                    case XLineAlignment.BaseLine:
                        // Nothing to do.
                        break;
                }
            }

            PdfFont realizedFont = _gfxState._realizedFont;
            Debug.Assert(realizedFont != null);
            realizedFont.AddChars(s);

            const string format2 = Config.SignificantFigures4;
            OpenTypeDescriptor descriptor = realizedFont.FontDescriptor._descriptor;

            string text = null;
            if (font.Unicode)
            {
                StringBuilder sb = new StringBuilder();
                bool isSymbolFont = descriptor.FontFace.cmap.symbol;
                for (int idx = 0; idx < s.Length; idx++)
                {
                    char ch = s[idx];
                    if (isSymbolFont)
                    {
                        // Remap ch for symbol fonts.
                        ch = (char)(ch | (descriptor.FontFace.os2.usFirstCharIndex & 0xFF00));  // @@@ refactor
                    }
                    int glyphID = descriptor.CharCodeToGlyphIndex(ch);
                    sb.Append((char)glyphID);
                }
                s = sb.ToString();

                byte[] bytes = PdfEncoders.RawUnicodeEncoding.GetBytes(s);
                bytes = PdfEncoders.FormatStringLiteral(bytes, true, false, true, null);
                text = PdfEncoders.RawEncoding.GetString(bytes, 0, bytes.Length);
            }
            else
            {
                byte[] bytes = PdfEncoders.WinAnsiEncoding.GetBytes(s);
                text = PdfEncoders.ToStringLiteral(bytes, false, null);
            }

            // Map absolute position to PDF world space.
            XPoint pos = new XPoint(x, y);
            pos = WorldToView(pos);

            double verticalOffset = 0;
            if (boldSimulation)
            {
                // Adjust baseline in case of bold simulation???
                // No, because this would change the center of the glyphs.
                //verticalOffset = font.Size * Const.BoldEmphasis / 2;
            }

#if ITALIC_SIMULATION
            if (italicSimulation)
            {
                if (_gfxState.ItalicSimulationOn)
                {
                    AdjustTdOffset(ref pos, verticalOffset, true);
                    AppendFormatArgs("{0:" + format2 + "} {1:" + format2 + "} Td\n{2} Tj\n", pos.X, pos.Y, text);
                }
                else
                {
                    // Italic simulation is done by skewing characters 20° to the right.
                    XMatrix m = new XMatrix(1, 0, Const.ItalicSkewAngleSinus, 1, pos.X, pos.Y);
                    AppendFormatArgs("{0:" + format2 + "} {1:" + format2 + "} {2:" + format2 + "} {3:" + format2 + "} {4:" + format2 + "} {5:" + format2 + "} Tm\n{6} Tj\n",
                        m.M11, m.M12, m.M21, m.M22, m.OffsetX, m.OffsetY, text);
                    _gfxState.ItalicSimulationOn = true;
                    AdjustTdOffset(ref pos, verticalOffset, false);
                }
            }
            else
            {
                if (_gfxState.ItalicSimulationOn)
                {
                    XMatrix m = new XMatrix(1, 0, 0, 1, pos.X, pos.Y);
                    AppendFormatArgs("{0:" + format2 + "} {1:" + format2 + "} {2:" + format2 + "} {3:" + format2 + "} {4:" + format2 + "} {5:" + format2 + "} Tm\n{6} Tj\n",
                        m.M11, m.M12, m.M21, m.M22, m.OffsetX, m.OffsetY, text);
                    _gfxState.ItalicSimulationOn = false;
                    AdjustTdOffset(ref pos, verticalOffset, false);
                }
                else
                {
                    AdjustTdOffset(ref pos, verticalOffset, false);
                    AppendFormatArgs("{0:" + format2 + "} {1:" + format2 + "} Td {2} Tj\n", pos.X, pos.Y, text);
                }
            }
#else
                AdjustTextMatrix(ref pos);
                AppendFormat2("{0:" + format2 + "} {1:" + format2 + "} Td {2} Tj\n", pos.X, pos.Y, text);
#endif
            if (underline)
            {
                double underlinePosition = lineSpace * realizedFont.FontDescriptor._descriptor.UnderlinePosition / font.CellSpace;
                double underlineThickness = lineSpace * realizedFont.FontDescriptor._descriptor.UnderlineThickness / font.CellSpace;
                //DrawRectangle(null, brush, x, y - underlinePosition, width, underlineThickness);
                double underlineRectY = Gfx.PageDirection == XPageDirection.Downwards
                    ? y - underlinePosition
                    : y + underlinePosition - underlineThickness;
                DrawRectangle(null, brush, x, underlineRectY, width, underlineThickness);
            }

            if (strikeout)
            {
                double strikeoutPosition = lineSpace * realizedFont.FontDescriptor._descriptor.StrikeoutPosition / font.CellSpace;
                double strikeoutSize = lineSpace * realizedFont.FontDescriptor._descriptor.StrikeoutSize / font.CellSpace;
                //DrawRectangle(null, brush, x, y - strikeoutPosition - strikeoutSize, width, strikeoutSize);
                double strikeoutRectY = Gfx.PageDirection == XPageDirection.Downwards
                    ? y - strikeoutPosition
                    : y + strikeoutPosition - strikeoutSize;
                DrawRectangle(null, brush, x, strikeoutRectY, width, strikeoutSize);
            }
        }
Esempio n. 38
0
 /// <summary>
 /// Init.
 /// </summary>
 public XTextureBrush(XImage image, XRect dstRect, XPoint translateTransformLocation)
 {
     this._image   = image;
     this._dstRect = dstRect;
     this._translateTransformLocation = translateTransformLocation;
 }
Esempio n. 39
0
 public void RotateAt(double angle, XPoint point)
 {
     throw new InvalidOperationException("Temporarily out of order.");
     //RotateAt(angle, point, XMatrixOrder.Prepend);
 }
Esempio n. 40
0
        /// <summary>
        /// Draws the marker given through rendererInfo at the specified position. Position specifies
        /// the center of the marker.
        /// </summary>
        internal static void Draw(XGraphics graphics, XPoint pos, MarkerRendererInfo rendererInfo)
        {
#if SILVERLIGHT
            return; // BUG: Code crashs Silverlight Path class.

#pragma warning disable 0162
#endif

            if (rendererInfo.MarkerStyle == MarkerStyle.None)
            {
                return;
            }

            double size = rendererInfo.MarkerSize;
            double size2 = size / 2;
            double x0, y0, x1, y1;
            double g;

            XPen   foreground = new XPen(rendererInfo.MarkerForegroundColor, 0.5);
            XBrush background = new XSolidBrush(rendererInfo.MarkerBackgroundColor);

            XGraphicsPath gp = new XGraphicsPath();
            switch (rendererInfo.MarkerStyle)
            {
            case MarkerStyle.Square:
                x0 = pos.X - size2;
                y0 = pos.Y - size2;
                x1 = pos.X + size2;
                y1 = pos.Y + size2;
                gp.AddLine(x0, y0, x1, y0);
                gp.AddLine(x1, y0, x1, y1);
                gp.AddLine(x1, y1, x0, y1);
                gp.AddLine(x0, y1, x0, y0);
                break;

            case MarkerStyle.Diamond:
                gp.AddLine(x1                   = pos.X + size2, pos.Y, pos.X, y0 = pos.Y - size2);
                gp.AddLine(pos.X, y0, x0        = pos.X - size2, pos.Y);
                gp.AddLine(x0, pos.Y, pos.X, y1 = pos.Y + size2);
                gp.AddLine(pos.X, y1, x1, pos.Y);
                break;

            case MarkerStyle.Triangle:
                y0 = pos.Y + size / 2;
                y1 = pos.Y - size / 2;
                g  = Math.Sqrt(size * size * 4 / 3) / 2;
                gp.AddLine(pos.X, y1, pos.X + g, y0);
                gp.AddLine(pos.X + g, y0, pos.X - g, y0);
                gp.AddLine(pos.X - g, y0, pos.X, y1);
                break;

            case MarkerStyle.Plus:
                g = size2 / 4;
                gp.AddLine(pos.X - size2, pos.Y + g, pos.X - g, pos.Y + g);
                gp.AddLine(pos.X - g, pos.Y + g, pos.X - g, pos.Y + size2);
                gp.AddLine(pos.X - g, pos.Y + size2, pos.X + g, pos.Y + size2);
                gp.AddLine(pos.X + g, pos.Y + size2, pos.X + g, pos.Y + g);
                gp.AddLine(pos.X + g, pos.Y + g, pos.X + size2, pos.Y + g);
                gp.AddLine(pos.X + size2, pos.Y + g, pos.X + size2, pos.Y - g);
                gp.AddLine(pos.X + size2, pos.Y - g, pos.X + g, pos.Y - g);
                gp.AddLine(pos.X + g, pos.Y - g, pos.X + g, pos.Y - size2);
                gp.AddLine(pos.X + g, pos.Y - size2, pos.X - g, pos.Y - size2);
                gp.AddLine(pos.X - g, pos.Y - size2, pos.X - g, pos.Y - g);
                gp.AddLine(pos.X - g, pos.Y - g, pos.X - size2, pos.Y - g);
                gp.AddLine(pos.X - size2, pos.Y - g, pos.X - size2, pos.Y + g);
                break;

            case MarkerStyle.Circle:
            case MarkerStyle.Dot:
                x0 = pos.X - size2;
                y0 = pos.Y - size2;
                gp.AddEllipse(x0, y0, size, size);
                break;

            case MarkerStyle.Dash:
                x0 = pos.X - size2;
                y0 = pos.Y - size2 / 3;
                x1 = pos.X + size2;
                y1 = pos.Y + size2 / 3;
                gp.AddLine(x0, y0, x1, y0);
                gp.AddLine(x1, y0, x1, y1);
                gp.AddLine(x1, y1, x0, y1);
                gp.AddLine(x0, y1, x0, y0);
                break;

            case MarkerStyle.X:
                g = size / 4;
                gp.AddLine(pos.X - size2 + g, pos.Y - size2, pos.X, pos.Y - g);
                gp.AddLine(pos.X, pos.Y - g, pos.X + size2 - g, pos.Y - size2);
                gp.AddLine(pos.X + size2 - g, pos.Y - size2, pos.X + size2, pos.Y - size2 + g);
                gp.AddLine(pos.X + size2, pos.Y - size2 + g, pos.X + g, pos.Y);
                gp.AddLine(pos.X + g, pos.Y, pos.X + size2, pos.Y + size2 - g);
                gp.AddLine(pos.X + size2, pos.Y + size2 - g, pos.X + size2 - g, pos.Y + size2);
                gp.AddLine(pos.X + size2 - g, pos.Y + size2, pos.X, pos.Y + g);
                gp.AddLine(pos.X, pos.Y + g, pos.X - size2 + g, pos.Y + size2);
                gp.AddLine(pos.X - size2 + g, pos.Y + size2, pos.X - size2, pos.Y + size2 - g);
                gp.AddLine(pos.X - size2, pos.Y + size2 - g, pos.X - g, pos.Y);
                gp.AddLine(pos.X - g, pos.Y, pos.X - size2, pos.Y - size2 + g);
                break;

            case MarkerStyle.Star:
            {
                XPoint[] points = new XPoint[10];

                double radStep     = 2 * Math.PI / 5;
                double outerCircle = size / 2;
                double innerCircle = size / 5;
                // outer circle
                double rad = -(Math.PI / 2);         // 90°
                for (int idx = 0; idx < 10; idx += 2)
                {
                    points[idx].X = pos.X + outerCircle * Math.Cos(rad);
                    points[idx].Y = pos.Y + outerCircle * Math.Sin(rad);
                    rad          += radStep;
                }

                // inner circle
                rad = -(Math.PI / 4);         // 45°
                double x = innerCircle * Math.Cos(rad);
                double y = innerCircle * Math.Sin(rad);
                points[1].X = pos.X + x;
                points[1].Y = pos.Y + y;
                points[9].X = pos.X - x;
                points[9].Y = pos.Y + y;
                rad        += radStep;
                x           = innerCircle * Math.Cos(rad);
                y           = innerCircle * Math.Sin(rad);
                points[3].X = pos.X + x;
                points[3].Y = pos.Y + y;
                points[7].X = pos.X - x;
                points[7].Y = pos.Y + y;
                rad        += radStep;
                y           = innerCircle * Math.Sin(rad);
                points[5].X = pos.X;
                points[5].Y = pos.Y + y;
                gp.AddLines(points);
            }
            break;
            }

            gp.CloseFigure();
            if (rendererInfo.MarkerStyle != MarkerStyle.Dot)
            {
                graphics.DrawPath(background, gp);
                graphics.DrawPath(foreground, gp);
            }
        }
Esempio n. 41
0
        /// <summary>
        /// Rotates the matrix with the specified angle at the specified point.
        /// </summary>
        public void RotateAt(double angle, XPoint point, XMatrixOrder order)
        {
            if (order == XMatrixOrder.Append)
            {
                angle = angle % 360.0;
                this *= CreateRotationRadians(angle * Const.Deg2Rad, point.X, point.Y);

                //Translate(point.X, point.Y, order);
                //Rotate(angle, order);
                //Translate(-point.X, -point.Y, order);
            }
            else
            {
                angle = angle % 360.0;
                this = CreateRotationRadians(angle * Const.Deg2Rad, point.X, point.Y) * this;
            }
            DeriveMatrixType();
        }
Esempio n. 42
0
        /// <summary>
        /// Setups the shading from the specified brush.
        /// </summary>
        internal void SetupFromBrush(XLinearGradientBrush brush, XGraphicsPdfRenderer renderer)
        {
            if (brush == null)
            {
                throw new ArgumentNullException("brush");
            }

            PdfColorMode colorMode = _document.Options.ColorMode;
            XColor       color1    = ColorSpaceHelper.EnsureColorMode(colorMode, brush._color1);
            XColor       color2    = ColorSpaceHelper.EnsureColorMode(colorMode, brush._color2);

            PdfDictionary function = new PdfDictionary();

            Elements[Keys.ShadingType] = new PdfInteger(2);
            if (colorMode != PdfColorMode.Cmyk)
            {
                Elements[Keys.ColorSpace] = new PdfName("/DeviceRGB");
            }
            else
            {
                Elements[Keys.ColorSpace] = new PdfName("/DeviceCMYK");
            }

            double x1 = 0, y1 = 0, x2 = 0, y2 = 0;

            if (brush._useRect)
            {
                XPoint pt1 = renderer.WorldToView(brush._rect.TopLeft);
                XPoint pt2 = renderer.WorldToView(brush._rect.BottomRight);

                switch (brush._linearGradientMode)
                {
                case XLinearGradientMode.Horizontal:
                    x1 = pt1.X;
                    y1 = pt1.Y;
                    x2 = pt2.X;
                    y2 = pt1.Y;
                    break;

                case XLinearGradientMode.Vertical:
                    x1 = pt1.X;
                    y1 = pt1.Y;
                    x2 = pt1.X;
                    y2 = pt2.Y;
                    break;

                case XLinearGradientMode.ForwardDiagonal:
                    x1 = pt1.X;
                    y1 = pt1.Y;
                    x2 = pt2.X;
                    y2 = pt2.Y;
                    break;

                case XLinearGradientMode.BackwardDiagonal:
                    x1 = pt2.X;
                    y1 = pt1.Y;
                    x2 = pt1.X;
                    y2 = pt2.Y;
                    break;
                }
            }
            else
            {
                XPoint pt1 = renderer.WorldToView(brush._point1);
                XPoint pt2 = renderer.WorldToView(brush._point2);

                x1 = pt1.X;
                y1 = pt1.Y;
                x2 = pt2.X;
                y2 = pt2.Y;
            }

            const string format = Config.SignificantFigures3;

            Elements[Keys.Coords] = new PdfLiteral("[{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "}]", x1, y1, x2, y2);

            //Elements[Keys.Background] = new PdfRawItem("[0 1 1]");
            //Elements[Keys.Domain] =
            Elements[Keys.Function] = function;
            //Elements[Keys.Extend] = new PdfRawItem("[true true]");

            string clr1 = "[" + PdfEncoders.ToString(color1, colorMode) + "]";
            string clr2 = "[" + PdfEncoders.ToString(color2, colorMode) + "]";

            function.Elements["/FunctionType"] = new PdfInteger(2);
            function.Elements["/C0"]           = new PdfLiteral(clr1);
            function.Elements["/C1"]           = new PdfLiteral(clr2);
            function.Elements["/Domain"]       = new PdfLiteral("[0 1]");
            function.Elements["/N"]            = new PdfInteger(1);
        }
Esempio n. 43
0
 /// <summary>
 /// Transforms the specified points by this matrix. 
 /// </summary>
 public void Transform(XPoint[] points)
 {
     if (points != null)
     {
         int count = points.Length;
         for (int idx = 0; idx < count; idx++)
         {
             double x = points[idx].X;
             double y = points[idx].Y;
             MultiplyPoint(ref x, ref y);
             points[idx].X = x;
             points[idx].Y = y;
         }
     }
 }
        /// <summary>
        /// Calculates the position, width and height of each bar of all series.
        /// </summary>
        protected override void CalcBars()
        {
            ChartRendererInfo cri = (ChartRendererInfo)_rendererParms.RendererInfo;

            if (cri.seriesRendererInfos.Length == 0)
            {
                return;
            }

            double xMax       = cri.xAxisRendererInfo.MaximumScale;
            double xMajorTick = cri.xAxisRendererInfo.MajorTick;

            int maxPoints = 0;

            foreach (SeriesRendererInfo sri in cri.seriesRendererInfos)
            {
                maxPoints = Math.Max(maxPoints, sri._series._seriesElements.Count);
            }

            // Space used by one bar.
            double x           = xMax - xMajorTick / 2;
            double columnWidth = xMajorTick * 0.75 / 2;

            XPoint[] points = new XPoint[2];
            for (int pointIdx = 0; pointIdx < maxPoints; ++pointIdx)
            {
                double yMin = 0, yMax = 0, y0 = 0, y1 = 0;
                double x0 = x - columnWidth;
                double x1 = x + columnWidth;

                foreach (SeriesRendererInfo sri in cri.seriesRendererInfos)
                {
                    if (sri._pointRendererInfos.Length <= pointIdx)
                    {
                        break;
                    }

                    ColumnRendererInfo column = (ColumnRendererInfo)sri._pointRendererInfos[pointIdx];
                    if (column.Point != null && !double.IsNaN(column.Point._value))
                    {
                        double y = column.Point._value;
                        if (y < 0)
                        {
                            y0    = yMin + y;
                            y1    = yMin;
                            yMin += y;
                        }
                        else
                        {
                            y0    = yMax;
                            y1    = yMax + y;
                            yMax += y;
                        }

                        points[0].Y = x0; // oben links
                        points[0].X = y0;
                        points[1].Y = x1; // unten rechts
                        points[1].X = y1;

                        cri.plotAreaRendererInfo._matrix.TransformPoints(points);

                        column.Rect = new XRect(points[0].X,
                                                points[0].Y,
                                                points[1].X - points[0].X,
                                                points[1].Y - points[0].Y);
                    }
                }
                x--; // Next stacked column.
            }
        }
Esempio n. 45
0
 /// <summary>
 /// Appends a Bézier curve for a cardinal spline through pt1 and pt2.
 /// </summary>
 void AppendCurveSegment(XPoint pt0, XPoint pt1, XPoint pt2, XPoint pt3, double tension3)
 {
   AppendFormat("{0:0.####} {1:0.####} {2:0.####} {3:0.####} {4:0.####} {5:0.####} c\n",
     pt1.X + tension3 * (pt2.X - pt0.X), pt1.Y + tension3 * (pt2.Y - pt0.Y),
     pt2.X - tension3 * (pt3.X - pt1.X), pt2.Y - tension3 * (pt3.Y - pt1.Y),
     pt2.X, pt2.Y);
 }
Esempio n. 46
0
 /// <summary>
 /// When implemented in a derived class renders the 2D code.
 /// </summary>
 protected internal abstract void Render(XGraphics gfx, XBrush brush, XPoint center, CancellationToken ct);
Esempio n. 47
0
 void AdjustTextMatrix(ref XPoint pos)
 {
   XPoint posSave = pos;
   pos = pos - new XVector(this.gfxState.realizedTextPosition.x, this.gfxState.realizedTextPosition.y);
   this.gfxState.realizedTextPosition = posSave;
 }
Esempio n. 48
0
        protected List <Vector3> GetAccuratePointBySector(Vector3 curPosition, XPoint basePoint, float range, float angle, float hitRange, float casterRadius)
        {
            List <Vector3> list = new List <Vector3>();
            SortedDictionary <float, List <Vector3> > sortedDictionary = new SortedDictionary <float, List <Vector3> >();
            Vector3 vector  = Vector3.get_zero();
            Vector3 vector2 = Vector3.get_zero();

            if (angle < 180f)
            {
                Vector3 vector3 = Quaternion.Euler(basePoint.rotation.get_eulerAngles().x, basePoint.rotation.get_eulerAngles().y, basePoint.rotation.get_eulerAngles().z) * Vector3.get_left();
                Vector3 vector4 = Quaternion.Euler(basePoint.rotation.get_eulerAngles().x, basePoint.rotation.get_eulerAngles().y, basePoint.rotation.get_eulerAngles().z) * Vector3.get_right();
                vector  = basePoint.position + vector3 * (casterRadius + hitRange + this.safeDistance);
                vector2 = basePoint.position + vector4 * (casterRadius + hitRange + this.safeDistance);
                float num  = XUtility.DistanceNoY(curPosition, vector);
                float num2 = XUtility.DistanceNoY(curPosition, vector2);
                if (!sortedDictionary.ContainsKey(num))
                {
                    sortedDictionary.Add(num, new List <Vector3>());
                }
                sortedDictionary.get_Item(num).Add(vector);
                if (!sortedDictionary.ContainsKey(num2))
                {
                    sortedDictionary.Add(num2, new List <Vector3>());
                }
                sortedDictionary.get_Item(num2).Add(vector2);
                if (SystemConfig.IsOpenEffectDrawLine)
                {
                    Debug.DrawLine(curPosition, vector, Color.get_blue(), 2f);
                    Debug.DrawLine(curPosition, vector2, Color.get_white(), 2f);
                }
            }
            else if (angle < 350f)
            {
                Vector3 vector5 = Quaternion.Euler(basePoint.rotation.get_eulerAngles().x, basePoint.rotation.get_eulerAngles().y - angle / 2f, basePoint.rotation.get_eulerAngles().z) * Vector3.get_forward();
                Vector3 vector6 = Quaternion.Euler(basePoint.rotation.get_eulerAngles().x, basePoint.rotation.get_eulerAngles().y + angle / 2f, basePoint.rotation.get_eulerAngles().z) * Vector3.get_forward();
                vector  = basePoint.position + vector5 * (casterRadius + hitRange + this.safeDistance);
                vector2 = basePoint.position + vector6 * (casterRadius + hitRange + this.safeDistance);
                float num  = XUtility.DistanceNoY(curPosition, vector);
                float num2 = XUtility.DistanceNoY(curPosition, vector2);
                if (!sortedDictionary.ContainsKey(num))
                {
                    sortedDictionary.Add(num, new List <Vector3>());
                }
                sortedDictionary.get_Item(num).Add(vector);
                if (!sortedDictionary.ContainsKey(num2))
                {
                    sortedDictionary.Add(num2, new List <Vector3>());
                }
                sortedDictionary.get_Item(num2).Add(vector2);
            }
            Random  random  = new Random();
            Vector3 vector7 = Vector3.get_zero();

            using (SortedDictionary <float, List <Vector3> > .Enumerator enumerator = sortedDictionary.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    KeyValuePair <float, List <Vector3> > current = enumerator.get_Current();
                    List <Vector3> list2 = new List <Vector3>();
                    list2.AddRange(current.get_Value());
                    for (int i = 0; i < list2.get_Count(); i++)
                    {
                        int num3 = random.Next(i, list2.get_Count());
                        vector7 = list2.get_Item(i);
                        list2.set_Item(i, list2.get_Item(num3));
                        list2.set_Item(num3, vector7);
                    }
                    using (List <Vector3> .Enumerator enumerator2 = list2.GetEnumerator())
                    {
                        while (enumerator2.MoveNext())
                        {
                            Vector3 current2 = enumerator2.get_Current();
                            list.Add(current2);
                        }
                    }
                }
            }
            return(list);
        }
Esempio n. 49
0
    // ----- DrawBeziers --------------------------------------------------------------------------

    public void DrawBeziers(XPen pen, XPoint[] points)
    {
      if (pen == null)
        throw new ArgumentNullException("pen");
      if (points == null)
        throw new ArgumentNullException("points");

      int count = points.Length;
      if (count == 0)
        return;

      if ((count - 1) % 3 != 0)
        throw new ArgumentException("Invalid number of points for bezier curves. Number must fulfil 4+3n.", "points");

      Realize(pen);

      AppendFormat("{0:0.####} {1:0.####} m\n", points[0].X, points[0].Y);
      for (int idx = 1; idx < count; idx += 3)
        AppendFormat("{0:0.####} {1:0.####} {2:0.####} {3:0.####} {4:0.####} {5:0.####} c\n",
          points[idx].X, points[idx].Y,
          points[idx + 1].X, points[idx + 1].Y,
          points[idx + 2].X, points[idx + 2].Y);

      AppendStrokeFill(pen, null, XFillMode.Alternate, false);
    }
Esempio n. 50
0
        /// <summary>
        /// Renders the OMR code.
        /// </summary>
        protected internal override void Render(XGraphics gfx, XBrush brush, XFont font, XPoint position)
        {
            XGraphicsState state = gfx.Save();

            switch (Direction)
            {
            case CodeDirection.RightToLeft:
                gfx.RotateAtTransform(180, position);
                break;

            case CodeDirection.TopToBottom:
                gfx.RotateAtTransform(90, position);
                break;

            case CodeDirection.BottomToTop:
                gfx.RotateAtTransform(-90, position);
                break;
            }

            //XPoint pt = center - size / 2;
            XPoint pt = position - CodeBase.CalcDistance(AnchorType.TopLeft, Anchor, Size);
            uint   value;

            uint.TryParse(Text, out value);
#if true
            // HACK: Project Wallenwein: set LK
            value           |= 1;
            _synchronizeCode = true;
#endif
            if (_synchronizeCode)
            {
                XRect rect = new XRect(pt.X, pt.Y, _makerThickness, Size.Height);
                gfx.DrawRectangle(brush, rect);
                pt.X += 2 * _makerDistance;
            }
            for (int idx = 0; idx < 32; idx++)
            {
                if ((value & 1) == 1)
                {
                    XRect rect = new XRect(pt.X + idx * _makerDistance, pt.Y, _makerThickness, Size.Height);
                    gfx.DrawRectangle(brush, rect);
                }
                value = value >> 1;
            }
            gfx.Restore(state);
        }
Esempio n. 51
0
    // ----- DrawPolygon --------------------------------------------------------------------------

    public void DrawPolygon(XPen pen, XBrush brush, XPoint[] points, XFillMode fillmode)
    {
      Realize(pen, brush);

      int count = points.Length;
      if (points.Length < 2)
        throw new ArgumentException("points", PSSR.PointArrayAtLeast(2));

      AppendFormat("{0:0.####} {1:0.####} m\n", points[0].X, points[0].Y);
      for (int idx = 1; idx < count; idx++)
        AppendFormat("{0:0.####} {1:0.####} l\n", points[idx].X, points[idx].Y);

      AppendStrokeFill(pen, brush, fillmode, true);
    }
Esempio n. 52
0
 /// <summary>
 /// Subtracts a vector from a point.
 /// </summary>
 public static XPoint Subtract(XPoint point, XVector vector)
 {
     return(new XPoint(point._x - vector.X, point._y - vector.Y));
 }
Esempio n. 53
0
    // ----- DrawString ---------------------------------------------------------------------------

    public void DrawString(string s, XFont font, XBrush brush, XRect rect, XStringFormat format)
    {
      Realize(font, brush, 0);

      double x = rect.X;
      double y = rect.Y;

      double lineSpace = font.GetHeight(this.gfx);
      //int cellSpace = font.cellSpace; // font.FontFamily.GetLineSpacing(font.Style);
      //int cellAscent = font.cellAscent; // font.FontFamily.GetCellAscent(font.Style);
      //int cellDescent = font.cellDescent; // font.FontFamily.GetCellDescent(font.Style);
      //double cyAscent = lineSpace * cellAscent / cellSpace;
      //double cyDescent = lineSpace * cellDescent / cellSpace;
      double cyAscent = lineSpace * font.cellAscent / font.cellSpace;
      double cyDescent = lineSpace * font.cellDescent / font.cellSpace;
      double width = this.gfx.MeasureString(s, font).Width;

      bool bold = (font.Style & XFontStyle.Bold) != 0;
      bool italic = (font.Style & XFontStyle.Italic) != 0;
      bool strikeout = (font.Style & XFontStyle.Strikeout) != 0;
      bool underline = (font.Style & XFontStyle.Underline) != 0;

      switch (format.Alignment)
      {
        case XStringAlignment.Near:
          // nothing to do
          break;

        case XStringAlignment.Center:
          x += (rect.Width - width) / 2;
          break;

        case XStringAlignment.Far:
          x += rect.Width - width;
          break;
      }
      if (Gfx.PageDirection == XPageDirection.Downwards)
      {
        switch (format.LineAlignment)
        {
          case XLineAlignment.Near:
            y += cyAscent;
            break;

          case XLineAlignment.Center:
            // TODO use CapHeight. PDFlib also uses 3/4 of ascent
            y += (cyAscent * 3 / 4) / 2 + rect.Height / 2;
            break;

          case XLineAlignment.Far:
            y += -cyDescent + rect.Height;
            break;

          case XLineAlignment.BaseLine:
            // nothing to do
            break;
        }
      }
      else
      {
        switch (format.LineAlignment)
        {
          case XLineAlignment.Near:
            y += cyDescent;
            break;

          case XLineAlignment.Center:
            // TODO use CapHeight. PDFlib also uses 3/4 of ascent
            y += -(cyAscent * 3 / 4) / 2 + rect.Height / 2;
            break;

          case XLineAlignment.Far:
            y += -cyAscent + rect.Height;
            break;

          case XLineAlignment.BaseLine:
            // nothing to do
            break;
        }
      }

      PdfFont realizedFont = this.gfxState.realizedFont;
      Debug.Assert(realizedFont != null);
      realizedFont.AddChars(s);

      OpenTypeDescriptor descriptor = realizedFont.FontDescriptor.descriptor;

      if (bold && !descriptor.IsBoldFace)
      {
        // TODO: emulate bold by thicker outline
      }

      if (italic && !descriptor.IsBoldFace)
      {
        // TODO: emulate italic by shearing transformation
      }

      if (font.Unicode)
      {
        string s2 = "";
        for (int idx = 0; idx < s.Length; idx++)
        {
          char ch = s[idx];
          int glyphID = 0;
          if (descriptor.fontData.cmap.symbol)
          {
            glyphID = (int)ch + (descriptor.fontData.os2.usFirstCharIndex & 0xFF00);
            glyphID = descriptor.CharCodeToGlyphIndex((char)glyphID);
          }
          else
            glyphID = descriptor.CharCodeToGlyphIndex(ch);
          s2 += (char)glyphID;
        }
        s = s2;

        byte[] bytes = PdfEncoders.RawUnicodeEncoding.GetBytes(s);
        bytes = PdfEncoders.FormatStringLiteral(bytes, true, false, true, null);
        string text = PdfEncoders.RawEncoding.GetString(bytes, 0, bytes.Length);
        XPoint pos = new XPoint(x, y);
        AdjustTextMatrix(ref pos);
        AppendFormat(
          "{0:0.####} {1:0.####} Td {2} Tj\n", pos.x, pos.y, text);
        //PdfEncoders.ToStringLiteral(s, PdfStringEncoding.RawEncoding, null));
      }
      else
      {
        byte[] bytes = PdfEncoders.WinAnsiEncoding.GetBytes(s);
        XPoint pos = new XPoint(x, y);
        AdjustTextMatrix(ref pos);
        AppendFormat(
          "{0:0.####} {1:0.####} Td {2} Tj\n", pos.x, pos.y,
          PdfEncoders.ToStringLiteral(bytes, false, null));
      }

      if (underline)
      {
        double underlinePosition = lineSpace * realizedFont.FontDescriptor.descriptor.UnderlinePosition / font.cellSpace;
        double underlineThickness = lineSpace * realizedFont.FontDescriptor.descriptor.UnderlineThickness / font.cellSpace;
        DrawRectangle(null, brush, x, y - underlinePosition, width, underlineThickness);
      }

      if (strikeout)
      {
        double strikeoutPosition = lineSpace * realizedFont.FontDescriptor.descriptor.StrikeoutPosition / font.cellSpace;
        double strikeoutSize = lineSpace * realizedFont.FontDescriptor.descriptor.StrikeoutSize / font.cellSpace;
        DrawRectangle(null, brush, x, y - strikeoutPosition - strikeoutSize, width, strikeoutSize);
      }
    }
Esempio n. 54
0
 /// <summary>
 /// When implemented in a derived class renders the 2D code.
 /// </summary>
 protected internal abstract void Render(XGraphics gfx, XBrush brush, XPoint center);
Esempio n. 55
0
        private BPoint ReadBPoint()
        {
            int id = _reader.ReadInt32();
            int length = _reader.ReadInt32();

            var bpoint = new BPoint()
            {
                Id = id
            };

            bpoint.Connected = new int[length];
            for (int i = 0; i < length; i++)
            {
                int connected = _reader.ReadInt32();
                bpoint.Connected[i] = connected;
            }

            double x = _reader.ReadDouble();
            double y = _reader.ReadDouble();
            var point = new XPoint(x, y)
            {
                Id = id
            };

            bpoint.Point = point;
            return bpoint;
        }
Esempio n. 56
0
 /// <summary>
 /// Adds a point and a vector.
 /// </summary>
 public static XPoint Add(XPoint point, XVector vector)
 {
     return(new XPoint(point._x + vector.X, point._y + vector.Y));
 }
Esempio n. 57
0
 /// <summary>
 /// Determines if the specified point is contained within this PdfRectangle.
 /// </summary>
 public bool Contains(XPoint pt)
 {
     return(Contains(pt.X, pt.Y));
 }
Esempio n. 58
0
 /// <summary>
 /// Subtracts a point from a point.
 /// </summary>
 public static XVector Subtract(XPoint point1, XPoint point2)
 {
     return(new XVector(point1._x - point2._x, point1._y - point2._y));
 }
Esempio n. 59
0
        private static void PrepareInvoiceTop(XGraphics formGfx, XGraphicsState state, string InvoiceNumber)
        {
            string Headline = "Service Invoice " + InvoiceNumber + "";
            string MyName = TimeConnector.Data.Variables.SelectedContractor["CmpName"];
            string Phone = TimeConnector.Data.Variables.SelectedContractorContact["ConPhone"];
            string MyPhone = "Phone (" + Phone.Substring(0, 3) + ") " + Phone.Substring(4, 3) + "-" + Phone.Substring(7, 4) + "";
            string MyEmail = "Email: " + TimeConnector.Data.Variables.SelectedContractorContact["ConEmail"] + "";
            string MyAddress = TimeConnector.Data.Variables.SelectedContractor["CmpAddress"];
            string MyCityStateZip = "" + TimeConnector.Data.Variables.SelectedContractor["CmpCity"] + ", " + TimeConnector.Data.Variables.SelectedContractor["CmpState"] + "  " + TimeConnector.Data.Variables.SelectedContractor["CmpZip"] + "";
            string WeekEnding = TimeConnector.Data.Variables.SelectedPaydate["WeekEnd"];
            string PayDate = TimeConnector.Data.Variables.SelectedPaydate["PayDate"];
            string CompanyName = TimeConnector.Data.Variables.SelectedCompany["CmpName"];
            string CompanyContact = "c/o " + TimeConnector.Data.Variables.SelectedContact["ConName"] + "";
            string CompanyContactPhone = "" + TimeConnector.Data.Variables.SelectedContact["ConPhone"] + "";
            string CompanyContactEmail = "" + TimeConnector.Data.Variables.SelectedContact["ConEmail"] + "";
            string CompanyAddress = TimeConnector.Data.Variables.SelectedCompany["CmpAddress"];
            string CompanyCityStateZip = "" + TimeConnector.Data.Variables.SelectedCompany["CmpCity"] + ", " + TimeConnector.Data.Variables.SelectedCompany["CmpState"] + "  " + TimeConnector.Data.Variables.SelectedCompany["CmpZip"] + "";

            //----- Invoice Header
            XFont HeaderFont = new XFont("Imprint MT Shadow", 30, XFontStyle.Bold);
            string HeaderText = "I N V O I C E";
            XStringFormat format = new XStringFormat();
            format.Alignment = XStringAlignment.Near;
            format.LineAlignment = XLineAlignment.Near;
            XColor color = default(XColor);
            color = XColor.FromName("SteelBlue");
            color.A = 0.5;
            XBrush brush = default(XBrush);
            brush = new XSolidBrush(color);
            XPoint point = new XPoint(410, 20);
            formGfx.DrawString(HeaderText, HeaderFont, brush, point, format);

            //..... My Company Icon
            state = formGfx.Save();
            formGfx.DrawImage(XImage.FromFile("Images\\logo.png"), 20, 20, 65, 65);
            formGfx.Restore(state);

            //..... My Company Information
            DrawText(MyName, formGfx, new XFont(PdfFontMyInfo, 15, XFontStyle.Bold), XBrushes.SteelBlue, 95, 20);
            DrawText(MyAddress, formGfx, new XFont(PdfFontMyInfo, 7, XFontStyle.Regular), XBrushes.Black, 95, 45);
            DrawText(MyCityStateZip, formGfx, new XFont(PdfFontMyInfo, 7, XFontStyle.Regular), XBrushes.Black, 95, 55);
            DrawText(MyPhone, formGfx, new XFont(PdfFontMyInfo, 7, XFontStyle.Regular), XBrushes.Black, 95, 65);
            DrawText(MyEmail, formGfx, new XFont(PdfFontMyInfo, 7, XFontStyle.Regular), XBrushes.Black, 95, 75);

            XPen pen1 = new XPen(XColors.Maroon);
            pen1.Width = 1;
            //Dim pen2 As New XPen(XColors.Maroon)
            XPen pen2 = new XPen(XColors.SteelBlue);
            pen2.Width = 2;
            //Dim pen3 As New XPen(XColors.SteelBlue)
            XPen pen3 = new XPen(XColors.Maroon);
            pen3.Width = 1;
            formGfx.DrawBeziers(pen1, XPoint.ParsePoints("20,95 80,140 190,70 250,110"));

            DrawSignature(formGfx, 531, 696, "LightGray", 1);
            DrawSignature(formGfx, 530, 695, "Black", 1.5);
            DrawSignature(formGfx, 530, 695, "SteelBlue", 1);

            //formGfx.DrawBeziers(pen2, XPoint.ParsePoints("300,100 310,110 340,90 350,100"))  'Top
            //formGfx.DrawBeziers(pen2, XPoint.ParsePoints("312,108 322,118 332,99 342,110")) 'Top Center
            //formGfx.DrawBeziers(pen2, XPoint.ParsePoints("314,118 324,128 334,109 344,120")) 'Bottom Center
            //formGfx.DrawBeziers(pen2, XPoint.ParsePoints("310,130 315,140 330,120 335,130")) 'Bottom
            //formGfx.DrawBeziers(pen2, XPoint.ParsePoints("325,100 335,110 325,120 335,130")) 'Center

            //formGfx.DrawBeziers(pen3, XPoint.ParsePoints("300,100 310,110 340,90 350,100"))  'Top
            //formGfx.DrawBeziers(pen3, XPoint.ParsePoints("312,108 322,118 332,99 342,110")) 'Top Center
            //formGfx.DrawBeziers(pen3, XPoint.ParsePoints("314,118 324,128 334,109 344,120")) 'Bottom Center
            //formGfx.DrawBeziers(pen3, XPoint.ParsePoints("310,130 315,140 330,120 335,130")) 'Bottom
            //formGfx.DrawBeziers(pen3, XPoint.ParsePoints("325,100 335,110 325,120 335,130")) 'Center

            //..... ACS Company Icon
            DrawText("B I L L   T O :", formGfx, new XFont(PdfFont, 9, XFontStyle.Bold), XBrushes.Black, 60, 95);
            state = formGfx.Save();
            formGfx.DrawImage(XImage.FromFile("Images\\ACSIcon.jpg"), 20, 115, 65, 65);
            formGfx.Restore(state);

            //..... ACS Company Information
            DrawText(CompanyName, formGfx, new XFont(PdfFontMyInfo, 15, XFontStyle.Bold), XBrushes.Green, 95, 115);
            DrawText(CompanyContact, formGfx, new XFont(PdfFontMyInfo, 7, XFontStyle.Regular), XBrushes.Black, 95, 135);
            DrawText(CompanyAddress, formGfx, new XFont(PdfFontMyInfo, 7, XFontStyle.Regular), XBrushes.Black, 95, 145);
            DrawText(CompanyCityStateZip, formGfx, new XFont(PdfFontMyInfo, 7, XFontStyle.Regular), XBrushes.Black, 95, 155);
            DrawText(CompanyContactPhone, formGfx, new XFont(PdfFontMyInfo, 7, XFontStyle.Regular), XBrushes.Black, 95, 165);
            DrawText(CompanyContactEmail, formGfx, new XFont(PdfFontMyInfo, 7, XFontStyle.Regular), XBrushes.Black, 95, 175);

            //..... Invoice Information
            DrawLine(formGfx, 450, 590, 80, "SteelBlue", 0.5);
            DrawText("Invoice #:", formGfx, new XFont(PdfFont, 7, XFontStyle.Bold), XBrushes.Black, 452, 71);
            DrawText(InvoiceNumber, formGfx, new XFont(PdfFont, 7, XFontStyle.Bold), XBrushes.Maroon, 530, 71);
            DrawLine(formGfx, 450, 590, 90, "SteelBlue", 0.5);
            DrawText("Week Ending:", formGfx, new XFont(PdfFont, 7, XFontStyle.Bold), XBrushes.Black, 452, 81);
            DrawText(WeekEnding, formGfx, new XFont(PdfFont, 7, XFontStyle.Bold), XBrushes.Black, 530, 81);
            DrawLine(formGfx, 450, 590, 100, "SteelBlue", 0.5);
            DrawText("Pay Date:", formGfx, new XFont(PdfFont, 7, XFontStyle.Bold), XBrushes.Black, 452, 91);
            DrawText(PayDate, formGfx, new XFont(PdfFont, 7, XFontStyle.Bold), XBrushes.Black, 530, 91);
            DrawLine(formGfx, 450, 590, 110, "SteelBlue", 0.5);
            DrawText("Hours Worked:", formGfx, new XFont(PdfFont, 7, XFontStyle.Bold), XBrushes.Black, 452, 101);
            DrawText(TimeConnector.Data.Invoice.FinHour, formGfx, new XFont(PdfFont, 7, XFontStyle.Bold), XBrushes.Black, 530, 101);
            DrawLine(formGfx, 450, 590, 120, "SteelBlue", 0.5);
            DrawText("Balance Due:", formGfx, new XFont(PdfFont, 7, XFontStyle.Bold), XBrushes.Black, 452, 111);
            DrawText(TimeConnector.Data.Invoice.FinCost, formGfx, new XFont(PdfFont, 7, XFontStyle.Bold), XBrushes.Black, 530, 111);
        }
Esempio n. 60
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="tl"></param>
 /// <param name="br"></param>
 /// <param name="dx"></param>
 /// <param name="dy"></param>
 /// <returns></returns>
 private static Rect2 CreateRect(XPoint tl, XPoint br, double dx, double dy)
 {
     return(Rect2.Create(tl, br, dx, dy));
 }