Пример #1
0
 public PDFTransformationMatrix(float offsetX, float offsetY, float angle, float scaleX, float scaleY)
     : this()
 {
     _matrix.Translate(offsetX, offsetY);
     _matrix.Rotate(angle);
     _matrix.Scale(scaleX, scaleY);
 }
Пример #2
0
        public void MouseWheelPictureBox(object sender, MouseEventArgs e)
        {
            Control eventCtrl = (Control)sender;

            /*各ディクショナリからコントロール名をキーに値を取得(値の変更がある場合、別途コミットが必要)*/
            System.Drawing.Drawing2D.Matrix targetMat = dicMat[eventCtrl.Name];

            //ポインタの位置→原点へ移動
            targetMat.Translate(-e.X, -e.Y, System.Drawing.Drawing2D.MatrixOrder.Append);
            if (e.Delta > 0)
            {
                //拡大
                if (targetMat.Elements[0] < 100) //X方向の倍率を代表してチェック
                {
                    targetMat.Scale(1.5f, 1.5f,
                                    System.Drawing.Drawing2D.MatrixOrder.Append);
                }
            }
            else
            {
                //縮小
                if (targetMat.Elements[0] > 0.01) //X方向の倍率を代表してチェック
                {
                    targetMat.Scale(1.0f / 1.5f, 1.0f / 1.5f,
                                    System.Drawing.Drawing2D.MatrixOrder.Append);
                }
            }
            //原点→ポインタの位置へ移動(元の位置へ戻す)
            targetMat.Translate(e.X, e.Y,
                                System.Drawing.Drawing2D.MatrixOrder.Append);

            //画像の描画
            DrawImage(eventCtrl);
        }
Пример #3
0
        private void DrawRotatedMeasureText(int gridSize, Graphics g, double degrees)
        {
            string text     = string.Format("{0} {1}", (double)(Math.Round(Length * ConversionRate, 1)), Unit);
            SizeF  textSize = g.MeasureString(text, measureFont);

            // Calculate the middle part of the segment
            Point start, end;

            start = Start.ToPoint(gridSize);
            end   = End.ToPoint(gridSize);
            PointF middlePoint = new PointF((start.X + end.X) / 2f, (start.Y + end.Y) / 2f);

            // we should find the middle of the segment and rotate based on that
            // at that point, we can easily translate it to not overlap the line
            using (System.Drawing.Drawing2D.Matrix transformMatrix = new System.Drawing.Drawing2D.Matrix())
            {
                // we rotate the text to match the slope of the line.
                transformMatrix.RotateAt((float)degrees, middlePoint);

                // translate by half the width
                transformMatrix.Translate(-textSize.Width / 2, 0);

                // if we want to put the text above the line, we need to translate the height as well.
                if ((Location & MeasurementLocation.Above) == MeasurementLocation.Above)
                {
                    transformMatrix.Translate(0, -textSize.Height);
                }

                g.Transform = transformMatrix;

                g.DrawString(text, measureFont, new SolidBrush(Color), middlePoint);

                g.ResetTransform();
            }
        }
Пример #4
0
        /// <summary>
        /// 画像をピクチャボックスのサイズに合わせて全体に表示するアフィン変換行列を求める
        /// </summary>
        /// <param name="mat">アフィン変換行列</param>
        /// <param name="image">画像データ</param>
        /// <param name="dst">描画先のピクチャボックス</param>
        private void ZoomFit(
            ref System.Drawing.Drawing2D.Matrix mat,
            ImagingSolution.Imaging.ImageData image,
            PictureBox dst)
        {
            // アフィン変換行列の初期化(単位行列へ)
            mat.Reset();

            int srcWidth  = image.Width;
            int srcHeight = image.Height;
            int dstWidth  = dst.Width;
            int dstHeight = dst.Height;

            float scale;

            // 縦に合わせるか?横に合わせるか?
            if (srcHeight * dstWidth > dstHeight * srcWidth)
            {
                // ピクチャボックスの縦方法に画像表示を合わせる場合
                scale = dstHeight / (float)srcHeight;
                mat.Scale(scale, scale, System.Drawing.Drawing2D.MatrixOrder.Append);
                // 中央へ平行移動
                mat.Translate((dstWidth - srcWidth * scale) / 2f, 0f, System.Drawing.Drawing2D.MatrixOrder.Append);
            }
            else
            {
                // ピクチャボックスの横方法に画像表示を合わせる場合
                scale = dstWidth / (float)srcWidth;
                mat.Scale(scale, scale, System.Drawing.Drawing2D.MatrixOrder.Append);
                // 中央へ平行移動
                mat.Translate(0f, (dstHeight - srcHeight * scale) / 2f, System.Drawing.Drawing2D.MatrixOrder.Append);
            }
        }
Пример #5
0
        protected override void CalculatePreTransform(Matrix cumulativeTransform)
        {
            if (_imagePosterior != null)
            {
                // when the posterior edge of the image can be determined,
                // apply an offset in addition to user-applied translations
                // this allows the image to appear initially at (and reset to)
                // a position where the posterior ("chest wall") is aligned
                // against an edge of the client rectangle.

                // compute the posterior vector according to the adjusted parameters
                var destPosteriorVector = GetCurrentPosteriorVector(_imagePosterior, SourceWidth, AdjustedSourceHeight, RotationXY, ScaleX, ScaleY, FlipX, FlipY);

                // check if posterior direction is along client X axis
                if (Math.Abs(destPosteriorVector.X) > Math.Abs(destPosteriorVector.Y))
                {
                    // compute additional horizontal translation to align posterior edge of image with client bounds
                    cumulativeTransform.Translate(Math.Sign(destPosteriorVector.X) * ((ClientRectangle.Width - Math.Abs(destPosteriorVector.X)) / 2f), 0);
                }
                else
                {
                    // compute additional vertical translation to align posterior edge of image with client bounds
                    cumulativeTransform.Translate(0, Math.Sign(destPosteriorVector.Y) * ((ClientRectangle.Height - Math.Abs(destPosteriorVector.Y)) / 2f));
                }
            }
            base.CalculatePreTransform(cumulativeTransform);
        }
        protected override void CalculatePreTransform(Matrix cumulativeTransform)
        {
            var destPosteriorVector = ScreenPosterior;

            if (destPosteriorVector != null)
            {
                // when the posterior edge of the image can be determined,
                // apply an offset in addition to user-applied translations
                // this allows the image to appear initially at (and reset to)
                // a position where the posterior ("chest wall") is aligned
                // against an edge of the client rectangle.

                // check if posterior direction is along client X axis
                if (Math.Abs(destPosteriorVector.X) > Math.Abs(destPosteriorVector.Y))
                {
                    // compute additional horizontal translation to align posterior edge of image with client bounds
                    cumulativeTransform.Translate(Math.Sign(destPosteriorVector.X) * ((ClientRectangle.Width - Math.Abs(destPosteriorVector.X)) / 2f), 0);
                }
                else
                {
                    // compute additional vertical translation to align posterior edge of image with client bounds
                    cumulativeTransform.Translate(0, Math.Sign(destPosteriorVector.Y) * ((ClientRectangle.Height - Math.Abs(destPosteriorVector.Y)) / 2f));
                }
            }
            base.CalculatePreTransform(cumulativeTransform);
        }
Пример #7
0
        /// <summary>
        /// 指定した点を中心に拡大縮小するアフィン変換行列の計算
        /// </summary>
        /// <param name="mat">アフィン変換行列</param>
        /// <param name="scale">拡大縮小の倍率</param>
        /// <param name="center">拡大縮小の中心座標</param>
        public static void ScaleAt(this System.Drawing.Drawing2D.Matrix mat, float scale, PointF center)
        {
            // 原点へ移動
            mat.Translate(-center.X, -center.Y, System.Drawing.Drawing2D.MatrixOrder.Append);

            // 拡大縮小
            mat.Scale(scale, scale, System.Drawing.Drawing2D.MatrixOrder.Append);

            // 元へ戻す
            mat.Translate(center.X, center.Y, System.Drawing.Drawing2D.MatrixOrder.Append);
        }
Пример #8
0
        public static Image RotateImage(Image inputImg, double degreeAngle)
        {
            //Corners of the image
            PointF[] rotationPoints = { new PointF(0,                            0),
                                        new PointF(inputImg.Width,               0),
                                        new PointF(0,              inputImg.Height),
                                        new PointF(inputImg.Width, inputImg.Height) };

            //Rotate the corners
            PointMath.RotatePoints(rotationPoints, new PointF(inputImg.Width / 2.0f, inputImg.Height / 2.0f), degreeAngle);

            //Get the new bounds given from the rotation of the corners
            //(avoid clipping of the image)
            Rectangle bounds = PointMath.GetBounds(rotationPoints);

            //An empy bitmap to draw the rotated image
            Bitmap rotatedBitmap = new Bitmap(bounds.Width, bounds.Height);

            using (Graphics g = Graphics.FromImage(rotatedBitmap))
            {
                g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                //Transformation matrix
                System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix();
                m.RotateAt((float)degreeAngle, new PointF(inputImg.Width / 2.0f, inputImg.Height / 2.0f));
                m.Translate(-bounds.Left, -bounds.Top, System.Drawing.Drawing2D.MatrixOrder.Append); //shift to compensate for the rotation

                g.Transform = m;
                g.DrawImage(inputImg, 0, 0);
            }
            return((Image)rotatedBitmap);
        }
 public override void ApplyTransformation(System.Drawing.Drawing2D.Matrix transform)
 {
     MoveX();
     MoveY();
     transform.Reset();
     transform.Translate(curX - fromX, curY - fromY);
 }
Пример #10
0
 /// <summary>
 /// 指定した点(point)周りの拡大縮小
 /// </summary>
 /// <param name="scale">倍率</param>
 /// <param name="point">基準点の座標</param>
 private void ScaleAt(
     ref System.Drawing.Drawing2D.Matrix mat,
     float scale,
     PointF point
     )
 {
     // 原点へ移動
     mat.Translate(-point.X, -point.Y,
                   System.Drawing.Drawing2D.MatrixOrder.Append);
     // 拡大縮小
     mat.Scale(scale, scale,
               System.Drawing.Drawing2D.MatrixOrder.Append);
     // 元へ戻す
     mat.Translate(point.X, point.Y,
                   System.Drawing.Drawing2D.MatrixOrder.Append);
 }
Пример #11
0
        /// <summary>
        /// Добавить штрихкод в каждую страницу файла pdf
        /// </summary>
        /// <param name="pdfFile">Файл pdf</param>
        /// <param name="code">Значение штрихкода</param>
        /// <param name="outFile">Выходной файл pdf</param>
        /// <param name="type">Тип бар кода, какие поддерживаются см. функцию CreateBarcode</param>
        /// <param name="offsetX">Смещение по X</param>
        /// <param name="offsetY">Смещение по Y</param>
        public static void BarcodeStamp(string pdfFile, string code, string outFile, string type = BarcodeType.Code128, int offsetX = 4, int offsetY = 4, int rotateDegrees = 270)
        {
            System.IO.FileStream fs      = new FileStream(outFile, FileMode.Create);
            PdfReader            reader  = new PdfReader(pdfFile);
            PdfStamper           stamper = new PdfStamper(reader, fs);
            int n = reader.NumberOfPages;

            iTextSharp.text.Rectangle pagesize;

            Barcode barcode = CreateBarcode(type, code);

            for (int i = 1; i <= n; i++)
            {
                PdfContentByte over = stamper.GetOverContent(i);

                // GetPageSize - возвращает размер без учета ориентации(альбомная, вертикальная), т.е. в случае альбомной width и height
                // будут перепутаны при отображении на экране и позиционировании, поэтому нужно делать GetPageSizeWithRotation.
                pagesize = reader.GetPageSizeWithRotation(i);

                PdfTemplate template = CreateBarcodeTemplate(over, barcode, true, true);

                // Добавить с поворотом
                var matrix = new System.Drawing.Drawing2D.Matrix();
                matrix.Translate(offsetX, offsetY);
                matrix.Rotate(rotateDegrees);

                float[] elements = matrix.Elements;
                over.AddTemplate(template, elements[0], elements[1], elements[2], elements[3], elements[4], elements[5]);
            }
            stamper.Close();
            reader.Close();
        }
Пример #12
0
        public static bool LineIntersectsRect(Matrix rayMatrix, Rectangle r)
        {
            Matrix m = rayMatrix.Clone();

            m.Translate(200, 0);
            return(LineIntersectsRect(new System.Drawing.Point((int)rayMatrix.OffsetX, (int)rayMatrix.OffsetY), new System.Drawing.Point((int)m.OffsetX, (int)m.OffsetY), r));
        }
Пример #13
0
        public void TestMatrix2()
        {
            System.Drawing.Drawing2D.Matrix mat = new System.Drawing.Drawing2D.Matrix();
            mat.Rotate(30);
            mat.Translate(-20, 20);

            var at = new AffineCoordinateTransformation2D(mat);
            var atInv = at.Inverse();

            var p0 = new double[] { 50d, 50d };
            var pt = at.Transform(p0);
            at.Invert();
            var p1 = at.Transform(pt);
            NUnit.Framework.Assert.LessOrEqual(System.Math.Abs(p1[0] - p0[0]), 0.01d);
            NUnit.Framework.Assert.LessOrEqual(System.Math.Abs(p1[1] - p0[1]), 0.01d);
            var p2 = atInv.Transform(pt);
            NUnit.Framework.Assert.LessOrEqual(System.Math.Abs(p2[0] - p0[0]), 0.01d);
            NUnit.Framework.Assert.LessOrEqual(System.Math.Abs(p2[1] - p0[1]), 0.01d);

            
            System.Drawing.PointF[] pts = new System.Drawing.PointF[] { new System.Drawing.PointF(50, 50) };

            mat.TransformPoints(pts);
            System.Diagnostics.Debug.WriteLine(string.Format("POINT ({0} {1})", pts[0].X, pts[0].Y));
            System.Drawing.PointF ptt = pts[0];
            System.Drawing.PointF[] ptts = new System.Drawing.PointF[] { new System.Drawing.PointF(ptt.X, ptt.Y) };
            System.Drawing.Drawing2D.Matrix inv = mat.Clone();
            inv.Invert();
            inv.TransformPoints(ptts);
            NUnit.Framework.Assert.LessOrEqual(System.Math.Abs(ptts[0].X - 50f), 0.01);
            NUnit.Framework.Assert.LessOrEqual(System.Math.Abs(ptts[0].Y - 50f), 0.01);

        }
Пример #14
0
        protected override void Draw(PdfContentByte cb)
        {
            //TODO if width and height not know: what to do
            //PdfTemplate template = cb.CreateTemplate(this.width, this.height);
            PdfTemplate template = cb.CreateTemplate(500, 500);

            //draw the list of elements on the new template
            foreach (IElement elem in this.list)
            {
                Graphic graphic = (Graphic)elem;

                if (applyCSSToElements)
                {
                    graphic.Draw(template, GetCombinedCss(graphic.GetCss(), GetCss()));
                }
                else
                {
                    graphic.Draw(template, graphic.GetCss());
                }
            }
            //add the template at the x, y position
            System.Drawing.Drawing2D.Matrix translation = new System.Drawing.Drawing2D.Matrix();
            translation.Translate(this.x, this.y);
            cb.ConcatCTM(translation);

            cb.Add(template);
        }
Пример #15
0
        public override void ApplyTransformation(System.Drawing.Drawing2D.Matrix transform)
        {
            if (toX == fromX)
            {
                curX = toX;
            }
            else if (fromX < toX)
            {
                curX += CHANGE_VALUE;
                if (curX >= toX)
                {
                    curX = toX;
                }
            }
            else
            {
                curX -= CHANGE_VALUE;
                if (curX <= toX)
                {
                    curX = toX;
                }
            }

            transform.Reset();

            transform.Translate(curX - fromX, 0);
            transform.RotateAt(-GetRotateAngle(curX), pivot);
        }
Пример #16
0
        private static byte[] CreatePdfWithArrayText(String directContentTj)
        {
            MemoryStream byteStream = new MemoryStream();

            Document  document = new Document();
            PdfWriter writer   = PdfWriter.GetInstance(document, byteStream);

            document.SetPageSize(PageSize.LETTER);

            document.Open();

            PdfContentByte cb = writer.DirectContent;

            BaseFont font = BaseFont.CreateFont();

            Matrix matrix = new Matrix();

            matrix.Translate(100, 500);
            cb.Transform(matrix);
            cb.BeginText();
            cb.SetFontAndSize(font, 12);

            cb.InternalBuffer.Append(directContentTj + "\n");

            cb.EndText();

            document.Close();

            byte[] pdfBytes = byteStream.ToArray();

            return(pdfBytes);
        }
Пример #17
0
        public override void ApplyTransformation(System.Drawing.Drawing2D.Matrix transform)
        {
            transform.Reset();
            if (fromScale != toScale)
            {
                if (small2Big)
                {
                    curScale += CHANGE_VALUE;
                    if (curScale >= toScale)
                    {
                        curScale  = toScale;
                        small2Big = false;
                        repeatCount++;
                    }
                }
                else
                {
                    curScale -= CHANGE_VALUE;
                    if (curScale <= fromScale)
                    {
                        curScale  = fromScale;
                        small2Big = true;
                    }
                }

                offsetX = pivotX * curScale - pivotX;
                offsetY = pivotY * curScale - pivotY;

                transform.Translate(-offsetX, -offsetY);
                transform.Scale(curScale, curScale);
            }
        }
Пример #18
0
 /// <summary> Translates the current transformation matrix by the given
 /// displacement.
 ///
 /// </summary>
 /// <param name="dx">x coordinate of the translation
 /// </param>
 /// <param name="dy">y coordinate of the translation
 /// </param>
 public virtual void translate(double dx, double dy)
 {
     System.Drawing.Drawing2D.Matrix temp_Matrix;
     temp_Matrix = new System.Drawing.Drawing2D.Matrix();
     temp_Matrix.Translate((float)dx, (float)dy);
     transform(temp_Matrix);
 }
Пример #19
0
        void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            var m = new System.Drawing.Drawing2D.Matrix();

            m.Translate(-this.hScrollBar.Value, -this.vScrollBar.Value);
            e.Graphics.Transform = m;

            foreach (Item item in this.lstLevel.Items)
            {
                if (item.IsVisible)
                {
                    item.Paint(e, State.Normal);
                }
            }

            foreach (Item item in this.lstPhysics.Items)
            {
                if (item.IsVisible)
                {
                    item.Paint(e, State.Normal);
                }
            }

            foreach (Item item in this.lstActors.Items)
            {
                if (item.IsVisible)
                {
                    item.Paint(e, State.Normal);
                }
            }
        }
        public void DrawString(Graphics graphics, string text, float fontSize, string fontEmphasis, string fontWeight, Brush brush, PointF point)
        {
            var x             = point.X;
            var y             = point.Y;
            var letterSpacing = 0.01f;

            foreach (var c in text)
            {
                var g = GetGlyph(fontWeight, fontEmphasis, c.ToString());

                if (g != null)
                {
                    var p = PathConverter.ConvertPath(new SVG.Path()
                    {
                        Commands = g.PathCommands
                    });

                    var m = new System.Drawing.Drawing2D.Matrix();

                    var sf = fontSize / 20.0f;

                    m.Scale(sf, sf);
                    m.Translate(x / sf, y / sf + 25f);

                    p.Transform(m);

                    graphics.FillPath(brush, p);

                    x += g.Width * sf + letterSpacing * fontSize * sf;
                }
            }
        }
Пример #21
0
        void GDIPaint(ScGraphics g, ScDrawNode node)
        {
            if (node == null)
            {
                return;
            }

            ScLayer layer = node.layer;

            if (node.rootLayer == null)
            {
                g.SetClip(node.clipRect);
                g.Transform = layer.GlobalMatrix;
                g.layer     = layer;
                layer.OnGDIPaint(g);
            }
            else
            {
                ScLayer rootLayer = node.rootLayer;

                Matrix m = new Matrix();
                m.Translate(-rootLayer.DrawBox.X, -rootLayer.DrawBox.Y);
                m.Multiply(layer.GlobalMatrix);

                g.SetClip(node.clipRect);
                g.Transform = m;
                g.layer     = layer;
                layer.OnGDIPaint(g);
                m.Dispose();
            }

            g.layer = null;
            g.ResetTransform();
            g.ResetClip();
        }
Пример #22
0
        public override void ApplyTransformation(System.Drawing.Drawing2D.Matrix transform)
        {
            transform.Reset();
            if (leftX != rightX)
            {
                if (left2Right)
                {
                    curX += CHANGE_VALUES;
                    if (curX >= rightX)
                    {
                        curX       = rightX;
                        left2Right = false;
                        repeatCount++;
                    }
                }
                else
                {
                    curX -= CHANGE_VALUES;
                    if (curX <= leftX)
                    {
                        curX       = leftX;
                        left2Right = true;
                    }
                }
            }

            transform.Shear(curX, 0);
            offset = pivotY * curX;
            transform.Translate(-offset, 0);
        }
Пример #23
0
        private static void CreateRotatedFillInBackground(Shape shape, Bitmap slideImage, double magnifyRatio = 1.0)
        {
            PPShape rotatedShape = new PPShape(shape, false);
            PointF  topLeftPoint = new PointF(rotatedShape.ActualTopLeft.X * GraphicsUtil.PictureExportingRatio,
                                              rotatedShape.ActualTopLeft.Y * GraphicsUtil.PictureExportingRatio);

            Bitmap rotatedImage = new Bitmap(slideImage.Width, slideImage.Height);

            using (Graphics g = Graphics.FromImage(rotatedImage))
            {
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                using (System.Drawing.Drawing2D.Matrix mat = new System.Drawing.Drawing2D.Matrix())
                {
                    mat.Translate(-topLeftPoint.X, -topLeftPoint.Y);
                    mat.RotateAt(-shape.Rotation, topLeftPoint);

                    g.Transform = mat;
                    g.DrawImage(slideImage, new Rectangle(0, 0, slideImage.Width, slideImage.Height));
                }
            }

            Bitmap magnifiedImage = KiCut(rotatedImage, 0, 0, shape.Width * GraphicsUtil.PictureExportingRatio,
                                          shape.Height * GraphicsUtil.PictureExportingRatio, magnifyRatio);

            magnifiedImage.Save(FillInBackgroundPicture, ImageFormat.Png);
        }
Пример #24
0
 public void DoPaintRemote(PaintEventArgs e)
 {
     var matrix = new System.Drawing.Drawing2D.Matrix();
     matrix.Translate(this.Left, this.Top);
     e.Graphics.Transform = matrix;
     OnPaint(e);
 }
Пример #25
0
        private void DrawInternal(System.Drawing.Graphics g, ICoordinateMapper coordinateMapper, System.Drawing.Rectangle renderingRect)
        {
            System.Drawing.Region oldClip = g.Clip;
            g.SetClip(renderingRect);

            System.Drawing.Drawing2D.Matrix oldMatrix = (System.Drawing.Drawing2D.Matrix)g.Transform.Clone();

            try
            {
                if (_rect.DrawMode == VObjectDrawMode.Normal)
                {
                    g.SmoothingMode     = normalSmoothingMode;
                    g.InterpolationMode = normalInterpolationMode;
                }
                else
                {
                    g.SmoothingMode     = draftSmoothingMode;
                    g.InterpolationMode = draftInterpolationMode;
                }

                System.Drawing.RectangleF bounds            = _rect.GetVObjectBounds();
                System.Drawing.RectangleF transformedBounds = _rect.GetTransformedVObjectBounds();
                System.Drawing.Rectangle  mappedBounds      = coordinateMapper.WorkspaceToControl(transformedBounds, Aurigma.GraphicsMill.Unit.Point);

                if (transformedBounds.Width > VObject.Eps && transformedBounds.Height > VObject.Eps)
                {
                    float scaleX = mappedBounds.Width / transformedBounds.Width,
                          scaleY = mappedBounds.Height / transformedBounds.Height;

                    using (System.Drawing.Drawing2D.Matrix outputMatrix = (System.Drawing.Drawing2D.Matrix)_rect.Transform.Clone())
                    {
                        outputMatrix.Translate(-transformedBounds.X, -transformedBounds.Y, System.Drawing.Drawing2D.MatrixOrder.Append);
                        outputMatrix.Scale(scaleX, scaleY, System.Drawing.Drawing2D.MatrixOrder.Append);
                        outputMatrix.Translate(mappedBounds.X, mappedBounds.Y, System.Drawing.Drawing2D.MatrixOrder.Append);

                        g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                        g.Transform       = outputMatrix;
                        g.DrawImage(this.DrawnImage, 0, 0, bounds.Width, bounds.Height);
                    }
                }
            }
            finally
            {
                g.Transform = oldMatrix;
                g.SetClip(oldClip, System.Drawing.Drawing2D.CombineMode.Replace);
            }
        }
Пример #26
0
        public void DoPaintRemote(PaintEventArgs e)
        {
            var matrix = new System.Drawing.Drawing2D.Matrix();

            matrix.Translate(this.Left, this.Top);
            e.Graphics.Transform = matrix;
            OnPaint(e);
        }
Пример #27
0
 private void MirrorPath(System.Drawing.Drawing2D.GraphicsPath GraphicPath)
 {
     System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix();
     m.Translate(0, Height - 1);
     m.Scale(1, -1);
     GraphicPath.Transform(m);
     m.Dispose();
 }
Пример #28
0
        protected virtual void SetTransform(System.Drawing.Drawing2D.Matrix transform, float scale)
        {
            offsetX = pivotX * scale - pivotX;
            offsetY = pivotY * scale - pivotY;

            transform.Translate(-offsetX, -offsetY);
            transform.Scale(scale, scale);
        }
        public override void ApplyTransformation(System.Drawing.Drawing2D.Matrix transform)
        {
            base.ApplyTransformation(transform);
            float scale = GetScale(curX);

            offsetX = width * scale - width;
            transform.Translate(-offsetX, 0);
            transform.Scale(GetScale(curX), 1);
        }
        public override bool CalculateCalloutLocation(out PointF location, out CoordinateSystem coordinateSystem)
        {
            if (this.Roi.Points.Count < 3 || string.IsNullOrEmpty(this.Callout.Text))
            {
                base.Callout.Visible = false;
            }
            else
            {
                base.Callout.Visible = true;
            }

            if (!base.Callout.Visible || _userMovedCallout)
            {
                return(base.CalculateCalloutLocation(out location, out coordinateSystem));
            }

            SizeF calloutOffsetDestination = GetCalloutOffsetDestination();

            coordinateSystem = CoordinateSystem.Destination;
            base.AnnotationGraphic.CoordinateSystem = coordinateSystem;

            // first, move the callout by the same amount the vertex moved (if it moved at all).
            location = base.Callout.TextLocation + calloutOffsetDestination;

            PointF start  = this.Roi.Points[0];
            PointF vertex = this.Roi.Points[1];
            PointF end    = this.Roi.Points[2];

            base.AnnotationGraphic.ResetCoordinateSystem();

            double vectorAngle = -Vector.SubtendedAngle(start, vertex, end) / 2 + 180;

            PointF[] points = new PointF[] { start, end };

            using (Matrix rotation = new Matrix())
            {
                rotation.Rotate((float)vectorAngle);
                rotation.Translate(-vertex.X, -vertex.Y);
                rotation.TransformPoints(points);
            }

            float calloutMagnitude = new Vector3D(location.X - vertex.X, location.Y - vertex.Y, 0).Magnitude;

            Vector3D startVector = new Vector3D(points[0].X, points[0].Y, 0);

            if (FloatComparer.AreEqual(startVector.Magnitude, 0F, 0.01F))
            {
                startVector = new Vector3D(-1, 0, 0);
            }

            startVector = startVector / startVector.Magnitude * calloutMagnitude;

            location = new PointF(startVector.X + vertex.X, startVector.Y + vertex.Y);

            return(true);
        }
Пример #31
0
        /// <summary> Adds a scene node to the scene at the given point.
        ///
        /// </summary>
        /// <param name="node">the scene node top be added
        /// </param>
        /// <param name="x">x coordinate of the point
        /// </param>
        /// <param name="y">y coordinate of the point
        /// </param>
        public virtual void add(SceneNode node, double x, double y)
        {
            System.Drawing.Drawing2D.Matrix temp_Matrix;
            temp_Matrix = new System.Drawing.Drawing2D.Matrix();
            temp_Matrix.Translate((float)x, (float)y);
            SceneTransform s = new SceneTransform(temp_Matrix);

            s.add(node);
            state.scene.add(s);
        }
Пример #32
0
        /// <summary>
        /// Draw all areas of the selected quest and highlight the selected area.
        /// </summary>
        private void Area_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.Clear(Area.BackColor);

            Matrix transformMatrix = new Matrix();
            transformMatrix.Rotate(90);
            transformMatrix.Multiply(new Matrix(-1, 0, 0, 1, 0, 0)); // Flip x-axis

            WoWQuestStep[] steps = ((QuestDisplayData)bsQuests.Current).Steps;

            float maxX = steps.Max(step => step.AreaPoints.Max(ap => ap.X));
            float maxY = steps.Max(step => step.AreaPoints.Max(ap => ap.Y));

            transformMatrix.Translate(-maxX - 5, -maxY - 5);

            e.Graphics.Transform = transformMatrix;

            // Draw all areas
            foreach (WoWQuestStep step in steps)
            {
                PointF[] drawPoints = ConvertToDrawingPoints(step.AreaPoints);
                if (drawPoints.Length < 3)
                {
                    foreach (PointF point in drawPoints)
                    {
                        // Draw a point 5x5 pixels
                        e.Graphics.FillEllipse(AREA_FILL, point.X - 2, point.Y - 2, 5F, 5F);
                        e.Graphics.DrawEllipse(AREA_BORDER, point.X - 2, point.Y - 2, 5F, 5F);
                    }
                }
                else
                {
                    e.Graphics.FillPolygon(AREA_FILL, drawPoints);
                    e.Graphics.DrawPolygon(AREA_BORDER, drawPoints);
                }
            }

            // Highlight selected area
            if (SelectedAreaPoints != null)
            {
                if (SelectedAreaPoints.Length < 3)
                {
                    foreach (PointF point in SelectedAreaPoints)
                    {
                        e.Graphics.FillEllipse(AREA_HIGHLIGHT, point.X - 2, point.Y - 2, 5F, 5F);
                        e.Graphics.DrawEllipse(AREA_BORDER, point.X - 2, point.Y - 2, 5F, 5F);
                    }
                }
                else
                {
                    e.Graphics.FillPolygon(AREA_HIGHLIGHT, this.SelectedAreaPoints);
                    e.Graphics.DrawPolygon(AREA_BORDER, this.SelectedAreaPoints);
                }
            }
        }
        protected override bool InitializeTransformMatrix()
        {
            if (this.CurveList == null)
             {
            this.IsInitialized = false;
            InvalidSerieException e = new InvalidSerieException("No data to display...");
            StockLog.Write(e);
            throw e;
             }
             if (this.GraphRectangle.Height > 0)
             {
            EventSeries.Clear();

            // Create fake Event Series;
            for (int i = 0; i < 5; i++)
            {
               EventSeries.Add(new BoolSerie(this.EndIndex, "Test" + i, i%2 == 0));
            }

            minValue = 0.0f;
            maxValue = EventSeries.Count + 1;

            if (graphic == null)
            {
               // Initialise graphics
               this.graphic = this.CreateGraphics();
               RectangleF rect = this.graphic.VisibleClipBounds;
               rect.Inflate(new SizeF(-this.XMargin, -this.YMargin));
               this.GraphRectangle = rect;
            }

            float coefX = (this.GraphRectangle.Width * 0.96f) / (EndIndex - StartIndex);
            float coefY = this.GraphRectangle.Height / (maxValue - minValue);

            matrixValueToScreen = new System.Drawing.Drawing2D.Matrix();
            matrixValueToScreen.Translate(this.GraphRectangle.X - (StartIndex - 0.5f) * coefX, maxValue * coefY + this.GraphRectangle.Y);
            matrixValueToScreen.Scale(coefX, -coefY);

            matrixScreenToValue = (System.Drawing.Drawing2D.Matrix)matrixValueToScreen.Clone();
            matrixScreenToValue.Invert();
             }
             else
             {
            this.Deactivate("App too small...", false);
            return false;
             }
             return true;
        }
Пример #34
0
        protected override bool InitializeTransformMatrix()
        {
            if (this.CurveList == null)
             {
            this.IsInitialized = false;
            InvalidSerieException e = new InvalidSerieException("No data to display...");
            StockLog.Write(e);
            throw e;
             }
             if (this.GraphRectangle.Height > 0)
             {
            minValue = float.MaxValue;
            maxValue = float.MinValue;
            this.CurveList.GetMinMax(StartIndex, EndIndex, ref minValue, ref maxValue, this.ScaleInvisible);

            if (minValue == maxValue || float.IsNaN(minValue) || float.IsInfinity(minValue) || float.IsNaN(maxValue) || float.IsInfinity(maxValue))
            {
               this.Deactivate("No volume for this stock", false);
               return false;
            }
            if (graphic == null)
            {
               // Initialise graphics
               this.graphic = this.CreateGraphics();
               RectangleF rect = this.graphic.VisibleClipBounds;
               rect.Inflate(new SizeF(-this.XMargin, -this.YMargin));
               this.GraphRectangle = rect;
            }

            float coefX = (this.GraphRectangle.Width * 0.96f) / (EndIndex - StartIndex);
            float coefY = this.GraphRectangle.Height / (maxValue - minValue);

            matrixValueToScreen = new System.Drawing.Drawing2D.Matrix();
            matrixValueToScreen.Translate(this.GraphRectangle.X - (StartIndex - 0.5f) * coefX, maxValue * coefY + this.GraphRectangle.Y);
            matrixValueToScreen.Scale(coefX, -coefY);

            matrixScreenToValue = (System.Drawing.Drawing2D.Matrix)matrixValueToScreen.Clone();
            matrixScreenToValue.Invert();
             }
             else
             {
            this.Deactivate("App too small...", false);
            return false;
             }
             return true;
        }
Пример #35
0
        protected override bool InitializeTransformMatrix()
        {
            if (float.IsNaN(this.RangeMin) || float.IsNaN(this.RangeMax))
             {
            return base.InitializeTransformMatrix();
             }

             if (this.CurveList == null)
             {
            this.IsInitialized = false;
            InvalidSerieException e = new InvalidSerieException("No data to display...");
            throw e;
             }
             if (this.CurveList.GetNbVisible() == 0)
             {
            this.Deactivate("No data to display...", false);
            return false;
             }
             if (this.StartIndex == this.EndIndex || this.EndIndex > this.dateSerie.Length - 1)
             {
            this.IsInitialized = false;
            InvalidSerieException e = new InvalidSerieException("Invalid input data range...");
            throw e;
             }
             if (this.GraphRectangle.Height > 0)
             {
            float minValue = this.RangeMin, maxValue = this.RangeMax;
            float coefX = (this.GraphRectangle.Width * 0.96f) / (EndIndex - StartIndex);
            float coefY = this.GraphRectangle.Height / (maxValue - minValue);

            matrixValueToScreen = new System.Drawing.Drawing2D.Matrix();
            matrixValueToScreen.Translate(this.GraphRectangle.X - (StartIndex - 0.5f) * coefX, maxValue * coefY + this.GraphRectangle.Y);
            matrixValueToScreen.Scale(coefX, -coefY);

            matrixScreenToValue = (System.Drawing.Drawing2D.Matrix)matrixValueToScreen.Clone();
            matrixScreenToValue.Invert();
            return true;
             }
             return false;
        }
Пример #36
0
        private void Carte_Paint(object sender, PaintEventArgs e)
        {
            int i;
            double w, h;
            //projet = ((Musliw.MusliW)(this.MdiParent)).projet;
            Graphics page = e.Graphics;

            //page.Clear(this.BackColor);

            w = this.Width;
            h = this.Height;

            Pen stylo = new Pen(fen.stylo_couleur, (int)fen.epaisseur);
            Font fonte = new Font(FontFamily.GenericSansSerif, 7,FontStyle.Bold);
            this.ForeColor = Color.Black;
            Brush brosse =new SolidBrush(fen.brosse_couleur);
            Brush brosse_texte = new SolidBrush(fen.couleur_texte);
            double dx = w / (projet.reseaux[nproj].xu - projet.reseaux[nproj].xl);
            double dy = h / (projet.reseaux[nproj].yu - projet.reseaux[nproj].yl);
            double deltax,deltay,voldeltax,voldeltay;
            double cx = 0.5f * (projet.reseaux[nproj].xu + projet.reseaux[nproj].xl);
            double cy = 0.5f * (projet.reseaux[nproj].yu + projet.reseaux[nproj].yl);

            //MessageBox.Show(xl.ToString() + " " + yu.ToString());
            PointF p1=new PointF();
            PointF p2 = new PointF();
            PointF p3 = new PointF();
            PointF p4 = new PointF();
            PointF p5 = new PointF();

            PointF[] points = new PointF[4] ;
               double angle=0,norme=0;
            double sinx = 0, cosx = 1;
            if (fen.volume_echelle < 1e-6f)
            {
                fen.volume_echelle = 1e-6f;
            }
            for (i = 0; i < projet.reseaux[nproj].links.Count; i++)
            {
                norme = fen.norme(projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].x, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].x, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].y, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].y, fen.ecart + 0.5f * fen.epaisseur);
                if ((projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].is_visible == true && projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].is_visible == true && norme > 0) && (projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].is_valid == true && projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].is_valid == true))
                {

                    //page.DrawRectangle(stylo, 0f, 0f, 200, 200);
                    //MessageBox.Show(((res.nodes[i].x - res.xl) * delta).ToString() + " " + ((res.yu - res.nodes[i].y) * delta).ToString()+" "+w.ToString()+" "+h.ToString());
                deltax = fen.deltax(projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].x, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].x, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].y, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].y, fen.ecart+0.5f*fen.epaisseur);
                deltay = fen.deltay(projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].x, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].x, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].y, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].y, fen.ecart+0.5f*fen.epaisseur);
                cosx = fen.deltax(projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].x, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].x, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].y, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].y, 1);
                sinx = fen.deltay(projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].x, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].x, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].y, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].y, 1);

                    voldeltax = fen.deltax(projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].x, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].x, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].y, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].y, fen.ecart + 0.5f * fen.epaisseur + projet.reseaux[projet.reseau_actif].links[i].volau / fen.volume_echelle);
                    voldeltay = fen.deltay(projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].x, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].x, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].y, projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].y, fen.ecart + 0.5f * fen.epaisseur + projet.reseaux[projet.reseau_actif].links[i].volau / fen.volume_echelle);
                    page.DrawLine(stylo, (float)(((projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].x - fen.xl) / fen.echelle) + deltay), (float)(((fen.yu - projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].y) / fen.echelle) + deltax),(float) (((projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].x - fen.xl) / fen.echelle) + deltay),(float) (((fen.yu - projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].y) / fen.echelle) + deltax));

                    p1.X = (float)(((projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].x - fen.xl) / fen.echelle) + deltay);
                    p1.Y = (float)(((fen.yu - projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].y) / fen.echelle) + deltax);
                    p2.X = (float)(((projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].x - fen.xl) / fen.echelle) + voldeltay);
                    p2.Y = (float)(((fen.yu - projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].no].y) / fen.echelle) + voldeltax);
                    p3.X = (float)(((projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].x - fen.xl) / fen.echelle) + voldeltay);
                    p3.Y = (float)(((fen.yu - projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].y) / fen.echelle) + voldeltax);
                    p4.X = (float)(((projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].x - fen.xl) / fen.echelle) + deltay);
                    p4.Y = (float)(((fen.yu - projet.reseaux[nproj].nodes[projet.reseaux[nproj].links[i].nd].y) / fen.echelle) + deltax);

                    System.Drawing.Drawing2D.GraphicsPath epaisseur = new System.Drawing.Drawing2D.GraphicsPath();
                    System.Drawing.Drawing2D.GraphicsPath texte_epaisseur = new System.Drawing.Drawing2D.GraphicsPath();
                    epaisseur.StartFigure();
                    points[0] = p1;
                    points[1] = p2;
                    points[2] = p3;
                    points[3] = p4;

                    epaisseur.AddPolygon(points);
                    epaisseur.CloseFigure();
                    //page.FillPath(brosse, epaisseur);
                    //page.FillPolygon(brosse, points);
                    //page.DrawPolygon(stylo,points);
                    epaisseur.Reset();
                    texte_epaisseur.StartFigure();
                    p5.X = 0.5f * (p3.X + p2.X);
                    p5.Y = 0.5f * (p3.Y + p2.Y);
                    texte_epaisseur.AddString(projet.reseaux[projet.reseau_actif].links[i].volau.ToString("0"), FontFamily.GenericSansSerif, 0, (float)fen.taille_texte, new PointF(p5.X, p5.Y), StringFormat.GenericDefault);
                    RectangleF encombrement = texte_epaisseur.GetBounds();
                    // texte_epaisseur.AddRectangle(encombrement);
                    //texte_epaisseur.AddPie(p5.X,p5.Y,2,2,0,360);

                    page.FillPolygon(brosse, points);
                    page.DrawPolygon(stylo, points);

                    if (encombrement.Width < fen.norme(p1.X, p4.X, p1.Y, p4.Y, 1) && projet.reseaux[projet.reseau_actif].links[i].volau > 0)
                    {
                        System.Drawing.Drawing2D.Matrix rotation = new System.Drawing.Drawing2D.Matrix();

                        if (cosx >= 0 && sinx <= 0)
                        {
                            angle = 180f * ((float)Math.Acos(cosx) / (float)Math.PI);
                            rotation.RotateAt((float)angle, p5);
                            rotation.Translate(p5.X - encombrement.X, p5.Y - encombrement.Y);
                            System.Drawing.Drawing2D.Matrix trans = new System.Drawing.Drawing2D.Matrix();
                            texte_epaisseur.Transform(rotation);
                            trans.Translate((float)(-0.5f * encombrement.Width * cosx),(float)( 0.5f * encombrement.Width * sinx));
                            texte_epaisseur.Transform(trans);
                            texte_epaisseur.CloseFigure();
                            page.FillPath(brosse_texte, texte_epaisseur);

                        }
                        else if (cosx <= 0 && sinx >= 0)
                        {
                            angle = 180f - 180f * ((float)Math.Acos(cosx) / (float)Math.PI);
                            rotation.RotateAt((float)angle, p5);
                            rotation.Translate(p5.X - encombrement.X, p5.Y - encombrement.Y);
                            System.Drawing.Drawing2D.Matrix trans = new System.Drawing.Drawing2D.Matrix();
                            texte_epaisseur.Transform(rotation);
                            trans.Translate((float)(+0.5f * encombrement.Width * cosx + (encombrement.Height) * sinx),(float)( -0.5f * encombrement.Width * sinx + (encombrement.Height) * cosx));
                            texte_epaisseur.Transform(trans);
                            texte_epaisseur.CloseFigure();

                            page.FillPath(brosse_texte, texte_epaisseur);

                        }
                        else if (cosx >= 0 && sinx >= 0)
                        {
                            angle = -180f * (float)Math.Acos(cosx) / (float)Math.PI;
                            rotation.RotateAt((float)angle, p5);
                            rotation.Translate(p5.X - encombrement.X, p5.Y - encombrement.Y);
                            System.Drawing.Drawing2D.Matrix trans = new System.Drawing.Drawing2D.Matrix();
                            texte_epaisseur.Transform(rotation);
                            trans.Translate((float)(-0.5f * encombrement.Width * cosx),(float)( 0.5f * encombrement.Width * sinx));
                            texte_epaisseur.Transform(trans);
                            texte_epaisseur.CloseFigure();

                            page.FillPath(brosse_texte, texte_epaisseur);
                        }
                        else if (cosx <= 0 && sinx <= 0)
                        {
                            angle = 180 + 180f * ((float)Math.Acos(cosx) / (float)Math.PI);
                            rotation.RotateAt((float)angle, p5);
                            rotation.Translate(p5.X - encombrement.X, p5.Y - encombrement.Y);
                            System.Drawing.Drawing2D.Matrix trans = new System.Drawing.Drawing2D.Matrix();
                            texte_epaisseur.Transform(rotation);
                            trans.Translate((float)(+0.5f * encombrement.Width * cosx + (encombrement.Height) * sinx),(float)( -0.5f * encombrement.Width * sinx + (encombrement.Height) * cosx));
                            texte_epaisseur.Transform(trans);
                            texte_epaisseur.CloseFigure();

                            page.FillPath(brosse_texte, texte_epaisseur);
                        }

                    }
                    epaisseur.Dispose();
                    texte_epaisseur.Dispose();
                }

            }
            /*        for (i = 0; i < projet.reseaux[nproj].nodes.Count; i++)
            {
                if (projet.reseaux[nproj].nodes[i].i != 0)
                {
                    //page.DrawRectangle(stylo, 0f, 0f, 200, 200);
                    //MessageBox.Show(((res.nodes[i].x - res.xl) * delta).ToString() + " " + ((res.yu - res.nodes[i].y) * delta).ToString()+" "+w.ToString()+" "+h.ToString());
                    page.FillRectangle(brosse, (res.nodes[i].x - res.xl) * delta, (res.yu - res.nodes[i].y) * delta, 30f, 20f);
                    page.DrawRectangle(stylo, (res.nodes[i].x - res.xl) * delta, (res.yu - res.nodes[i].y) * delta, 30f, 20f);
                    page.DrawString(res.nodes[i].i.ToString(), fonte, Brushes.Black, new RectangleF((res.nodes[i].x - res.xl) * delta, (res.yu - res.nodes[i].y) * delta, 30f, 20f));
                }
            }*/
        }
Пример #37
0
        /// <summary>
        /// When the element is called on to be painted this method is called
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPaint(PaintEventArgs e)
        {
                base.OnPaint(e);
                Bitmap tempBuffer = new Bitmap(Width, Height);
                Graphics tempGraph = Graphics.FromImage(tempBuffer);
                tempGraph.SmoothingMode = _drawingQuality;
                Rectangle inflatedInvalidationRect = Rectangle.Inflate(e.ClipRectangle,5,5);

                if (IsInitialized)
                {
                    tempGraph.DrawImage(_backBuffer, inflatedInvalidationRect, inflatedInvalidationRect, GraphicsUnit.Pixel);
                }
                else
                {
                    UpdateBackBuffer();
                    tempGraph.DrawImage(_backBuffer, new Point(0, 0));
                }

                //Draws selected shapes last 
                if (_modelElementsSelected.Count > 0)
                {
                    for (int i = _modelElementsSelected.Count - 1; i >= 0; i--)
                    {
                        ModelElement me = _modelElementsSelected[i];
                        System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix();
                        Point translator = VirtualToPixel(me.Location.X,me.Location.Y);
                        m.Translate(translator.X, translator.Y);
                        m.Scale(_virtualZoom, _virtualZoom);
                        tempGraph.Transform = m;
                        me.Paint(tempGraph);
                        tempGraph.Transform = new System.Drawing.Drawing2D.Matrix();
                    }
                }

                //If the users is dragging a select box we draw it here
                if (_selectBoxDraw)
                {
                    SolidBrush highlightBrush = new SolidBrush(Color.FromArgb(30,SystemColors.Highlight));
                    tempGraph.FillRectangle(highlightBrush, Rectangle.Inflate(_selectBox,-1,-1));
                    Rectangle outlineRect = new Rectangle(_selectBox.X, _selectBox.Y, _selectBox.Width - 1, _selectBox.Height - 1);
                    tempGraph.DrawRectangle(SystemPens.Highlight, outlineRect);

                    //garbage collection
                    highlightBrush.Dispose();
                }

                //Draws the temporary bitmap to the screen
                e.Graphics.SmoothingMode = _drawingQuality;
                e.Graphics.DrawImage(tempBuffer, inflatedInvalidationRect, inflatedInvalidationRect, GraphicsUnit.Pixel);

                //Garbage collection
                tempBuffer.Dispose();    
                tempGraph.Dispose();
        }
Пример #38
0
		/// <summary>
		/// Gives subclasses an opportunity to perform a post-transform transformation.
		/// </summary>
		protected virtual void CalculatePostTransform(Matrix cumulativeTransform)
		{
			cumulativeTransform.Translate(-_centerOfRotationXY.X, -_centerOfRotationXY.Y);
		}
Пример #39
0
        void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            var m = new System.Drawing.Drawing2D.Matrix();
             m.Translate(-this.hScrollBar.Value, -this.vScrollBar.Value);
             e.Graphics.Transform = m;

             foreach (Item item in this.lstLevel.Items)
            if (item.IsVisible)
               item.Paint(e, State.Normal);

             foreach (Item item in this.lstPhysics.Items)
            if (item.IsVisible)
               item.Paint(e, State.Normal);

             foreach (Item item in this.lstActors.Items)
            if (item.IsVisible)
               item.Paint(e, State.Normal);
        }
Пример #40
0
        /// <summary>
        /// Paints the elements to the backbuffer
        /// </summary>
        private void UpdateBackBuffer()
        {
            _backBuffer = new Bitmap(Width, Height);
            Graphics graph = Graphics.FromImage(_backBuffer);
            graph.SmoothingMode = _drawingQuality;
            graph.FillRectangle(Brushes.White, 0, 0, _backBuffer.Width, _backBuffer.Height);

            //When the backbuffer is updated this code draws the watermark
            if (_showWaterMark)
            {
                Bitmap watermark = Images.MapWindowLogoPale;
                if ((_backBuffer.Width > watermark.Width) && (_backBuffer.Height > watermark.Height))
                {
                    graph.DrawImage(watermark, _backBuffer.Width - watermark.Width - 18, _backBuffer.Height - watermark.Height -18 ,watermark.Width , watermark.Height);
                }
            }

            //Check if there are any model elements to draw
            foreach (ModelElement me in _modelElements)
            {
                if (_modelElementsSelected.Contains(me) == false)
                {
                    System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix();
                    Point translator = VirtualToPixel(new Point(me.Location.X, me.Location.Y));
                    m.Translate(translator.X,translator.Y);
                    m.Scale(_virtualZoom, _virtualZoom);
                    graph.Transform = m;
                    me.Paint(graph);
                    graph.Transform = new System.Drawing.Drawing2D.Matrix();
                }
            }

            //Updates is initialized
            IsInitialized = true;
        }
		public override bool CalculateCalloutLocation(out PointF location, out CoordinateSystem coordinateSystem)
		{
			if (this.Roi.Points.Count < 3 || string.IsNullOrEmpty(this.Callout.Text))
				base.Callout.Visible = false;
			else
				base.Callout.Visible = true;

			if (!base.Callout.Visible || _userMovedCallout)
				return base.CalculateCalloutLocation(out location, out coordinateSystem);

			SizeF calloutOffsetDestination = GetCalloutOffsetDestination();

			coordinateSystem = CoordinateSystem.Destination;
			base.AnnotationGraphic.CoordinateSystem = coordinateSystem;

			// first, move the callout by the same amount the vertex moved (if it moved at all).
			location = base.Callout.TextLocation + calloutOffsetDestination;

			PointF start = this.Roi.Points[0];
			PointF vertex = this.Roi.Points[1];
			PointF end = this.Roi.Points[2];

			base.AnnotationGraphic.ResetCoordinateSystem();

			double vectorAngle = -Vector.SubtendedAngle(start, vertex, end) / 2 + 180;

			PointF[] points = new PointF[] { start, end };

			using (Matrix rotation = new Matrix())
			{
				rotation.Rotate((float) vectorAngle);
				rotation.Translate(-vertex.X, -vertex.Y);
				rotation.TransformPoints(points);
			}

			float calloutMagnitude = new Vector3D(location.X - vertex.X, location.Y - vertex.Y, 0).Magnitude;

			Vector3D startVector = new Vector3D(points[0].X, points[0].Y, 0);
			if (FloatComparer.AreEqual(startVector.Magnitude, 0F, 0.01F))
				startVector = new Vector3D(-1, 0, 0);

			startVector = startVector / startVector.Magnitude * calloutMagnitude;

			location = new PointF(startVector.X + vertex.X, startVector.Y + vertex.Y);

			return true;
		}
        protected override bool InitializeTransformMatrix()
        {
            using (MethodLogger ml = new MethodLogger(this))
             {
            if (!CheckGraphSanity()) { return false; }
            if (this.GraphRectangle.Height > 0)
            {
               minValue = float.MaxValue;
               maxValue = float.MinValue;
               this.CurveList.GetMinMax(0, dateSerie.Length - 1, ref minValue, ref maxValue, this.ScaleInvisible);

               if (minValue == maxValue || minValue == float.MaxValue || float.IsNaN(minValue) || float.IsInfinity(minValue) || maxValue == float.MinValue || float.IsNaN(maxValue) || float.IsInfinity(maxValue))
               {
                  this.Deactivate("Input data is corrupted and cannot be displayed...", false);
                  return false;
               }

               if (this.IsLogScale && minValue > 0)
               {
                  minValue -= (maxValue - minValue) * 0.025f;
               }
               else
               {
                  minValue -= (maxValue - minValue) * 0.05f;
               }
               maxValue += (maxValue - minValue) * 0.05f;

               float tmpMinValue, tmpMaxValue;
               if (this.IsLogScale)
               {
                  tmpMinValue = minValue < 0 ? (float)-Math.Log10(-minValue + 1) : (float)Math.Log10(minValue + 1);
                  tmpMaxValue = maxValue < 0 ? (float)-Math.Log10(-maxValue + 1) : (float)Math.Log10(maxValue + 1);
               }
               else
               {
                  tmpMinValue = minValue;
                  tmpMaxValue = maxValue;
               }

               float coefX = (this.GraphRectangle.Width * 0.94f) / (dateSerie.Length - 1);
               float coefY = this.GraphRectangle.Height / (tmpMaxValue - tmpMinValue);

               matrixValueToScreen = new System.Drawing.Drawing2D.Matrix();
               matrixValueToScreen.Translate(this.GraphRectangle.X + 20, tmpMaxValue * coefY + this.GraphRectangle.Y);
               matrixValueToScreen.Scale(coefX, -coefY);

               matrixScreenToValue = (System.Drawing.Drawing2D.Matrix)matrixValueToScreen.Clone();
               matrixScreenToValue.Invert();
            }
            else
            {
               this.Deactivate("App too small...", false);
               return false;
            }
            return true;
             }
        }
Пример #43
0
            public void TestMatrix2()
            {
                System.Drawing.Drawing2D.Matrix mat = new System.Drawing.Drawing2D.Matrix();
                mat.Rotate(30);
                mat.Translate(-20, 20);

                var at = new AffineCoordinateTransformation2D(mat);
                var atInv = at.Inverse();

                var p0 = new double[] { 50d, 50d };
                var pt = at.Transform(p0);
                at.Invert();
                var p1 = at.Transform(pt);
                NUnit.Framework.Assert.LessOrEqual(System.Math.Abs(p1[0] - p0[0]), 0.01d);
                NUnit.Framework.Assert.LessOrEqual(System.Math.Abs(p1[1] - p0[1]), 0.01d);
                var p2 = atInv.Transform(pt);
                NUnit.Framework.Assert.LessOrEqual(System.Math.Abs(p2[0] - p0[0]), 0.01d);
                NUnit.Framework.Assert.LessOrEqual(System.Math.Abs(p2[1] - p0[1]), 0.01d);

                System.Drawing.PointF[] pts = new System.Drawing.PointF[] { new System.Drawing.PointF(50, 50) };

                mat.TransformPoints(pts);
                System.Diagnostics.Debug.WriteLine(string.Format("POINT ({0} {1})", pts[0].X, pts[0].Y));
                System.Drawing.PointF ptt = pts[0];
                System.Drawing.PointF[] ptts = new System.Drawing.PointF[] { new System.Drawing.PointF(ptt.X, ptt.Y) };
                System.Drawing.Drawing2D.Matrix inv = mat.Clone();
                inv.Invert();
                inv.TransformPoints(ptts);
                NUnit.Framework.Assert.LessOrEqual(System.Math.Abs(ptts[0].X - 50f), 0.01);
                NUnit.Framework.Assert.LessOrEqual(System.Math.Abs(ptts[0].Y - 50f), 0.01);
            }
        private void DrawFillPattern(Graphics g)
        {
            Stopwatch sw = Stopwatch.StartNew();
            float matrixScale;
            var fillPattern = FillPattern;
            if (fillPattern == null)
                return;

            if (fillPattern.Target == FillPatternTarget.Model)
                matrixScale = Scale;
            else
                matrixScale = Scale * 10;

            try
            {
                var width =
                    (ActualWidth == 0 ? Width : ActualWidth) == 0
                    ? 100
                    : (ActualWidth == 0 ? Width : ActualWidth);

                if (double.IsNaN(width))
                    width = 100;

                var height =
                    (ActualHeight == 0 ? Height : ActualHeight) == 0
                    ? 30
                    : (ActualHeight == 0 ? Height : ActualHeight);

                if (double.IsNaN(height))
                    height = 30;

                var viewRect = new Rectangle(0, 0,
                                             (int)width, (int)height);

                var centerX = (viewRect.Left + viewRect.Left
                               + viewRect.Width) / 2;

                var centerY = (viewRect.Top + viewRect.Top
                               + viewRect.Height) / 2;

                g.TranslateTransform(centerX, centerY);

                var rectF = new Rectangle(-1, -1, 2, 2);
                g.FillRectangle(Brushes.Blue, rectF); //draw a small rectangle in the center of the image

                g.ResetTransform();

                var fillGrids = fillPattern.GetFillGrids();

                Debug.Print(new string('-', 100));
                Debug.Print("FilPattern name: {0}", fillPattern.Name);
                if (fillPattern.Target == FillPatternTarget.Model)
                    Debug.Print("FillPattern type: Model");
                else
                    Debug.Print("FillPattern type: Drafting");
                Debug.Print("Matrix scale: {0}", matrixScale);
                Debug.Print("Grids count: {0}", fillGrids.Count);
                Debug.Print("Len\\Area: {0}", fillPattern.LengthPerArea);
                Debug.Print("Lines\\Len: {0}", fillPattern.LinesPerLength);
                Debug.Print("Strokes\\Area: {0}", fillPattern.StrokesPerArea);

                foreach (var fillGrid in fillGrids)
                {
                    var degreeAngle = (float)RadianToGradus(fillGrid.Angle);
                    Debug.Print(new string('-', 50));
                    Debug.Print("Origin: U:{0} V:{1}",
                                fillGrid.Origin.U, fillGrid.Origin.V);
                    Debug.Print("Offset: {0}", fillGrid.Offset);
                    Debug.Print("Angle: {0}", degreeAngle);
                    Debug.Print("Shift: {0}", fillGrid.Shift);

                    var pen = new Pen(System.Drawing.Color.Black)
                    {
                        Width = 1f / matrixScale
                    };

                    float dashLength = 1;
                    var segments = fillGrid.GetSegments();

                    if (segments.Count > 0)
                    {
                        pen.DashPattern = segments
                            .Select(Convert.ToSingle)
                            .ToArray();

                        Debug.Print("\tSegments:");
                        foreach (var segment in segments)
                        {
                            Debug.Print("\t\t{0}", segment);
                        }

                        dashLength = pen.DashPattern.Sum();
                    }

                    g.ResetTransform();
                    var rotateMatrix = new Matrix();
                    rotateMatrix.Rotate(degreeAngle);
                    var matrix = new Matrix(1, 0,
                                            0, -1,
                                            centerX, centerY); //-1 reflects about x-axis
                    matrix.Scale(matrixScale, matrixScale);
                    matrix.Translate((float)fillGrid.Origin.U,
                                     (float)fillGrid.Origin.V);
                    var backMatrix = matrix.Clone();
                    backMatrix.Multiply(rotateMatrix);
                    matrix.Multiply(rotateMatrix);

                    var offset = (-10) * dashLength;
                    matrix.Translate(offset, 0);
                    backMatrix.Translate(offset, 0);
                    Debug.Print("Offset: {0}", offset);

                    bool moving_forward = true;
                    bool moving_back = true;
                    int safety = 500;
                    double alternator = 0;
                    while (moving_forward || moving_back)    //draw segments shifting and offsetting each time
                    {
                        Debug.Write("*");
                        var rectF1 = new RectangleF(-2 / matrixScale, -2 / matrixScale, 4 / matrixScale, 4 / matrixScale);

                        if (moving_forward && LineIntersectsRect(matrix, viewRect))
                        {
                            g.Transform = matrix;
                            g.DrawLine(pen, new PointF(0, 0), new PointF(LENGTH, 0));
                        }
                        else
                        {
                            moving_forward = false;
                            Debug.Print("\n----> Matrix does not intersect view");
                        }

                        if (moving_back && LineIntersectsRect(backMatrix, viewRect))
                        {
                            g.Transform = backMatrix;
                            g.DrawLine(pen, new PointF(0, 0), new PointF(LENGTH, 0));
                        }
                        else
                        {
                            moving_back = false;
                            Debug.Print("\n----> Back matrix does not intersect view");
                        }

                        if (safety == 0)
                        {
                            Debug.Print("\n--------> Safety limit exceeded");
                            break;
                        }
                        else
                            --safety;

                        matrix.Translate((float)fillGrid.Shift,
                                         (float)fillGrid.Offset);
                        backMatrix.Translate(-(float)fillGrid.Shift,
                                             -(float)fillGrid.Offset);

                        alternator += fillGrid.Shift;
                        if (Math.Abs(alternator) > Math.Abs(offset))
                        {
                            Debug.Print("\n----> Alternating");
                            matrix.Translate(offset, 0);
                            backMatrix.Translate(offset, 0);
                            alternator = 0d;
                        }
                    }
                }
                sw.Stop();
                g.ResetTransform();
            #if DEBUG
                g.DrawString(string.Format("{0} ms",
                                           sw.ElapsedMilliseconds),
                             System.Drawing.SystemFonts.DefaultFont,
                             Brushes.Red, 0, 0);
            #endif
                Debug.Print(new string('-', 50));

                Pen p = new Pen(System.Drawing.Color.Black);
                p.Width = 1f / matrixScale;
                Debug.Print("Finished");
            }
            catch (Exception ex)
            {
                Debug.Print(ex.ToString());
            }
        }
Пример #45
0
			/// <summary>
			/// Bisects the inner angle formed by <paramref name="point1"/> <paramref name="point2"/> <paramref name="point3"/>.
			/// </summary>
			/// <remarks>
			/// <para>
			/// Based largely on <see cref="ProtractorRoiCalloutLocationStrategy"/>.
			/// </para>
			/// <para>
			/// The return value is a point within the angle such that the line segment
			/// from this point to <paramref name="point2"/> has the specified <paramref name="magnitude"/> and bisects the angle
			/// <paramref name="point1"/> <paramref name="point2"/> <paramref name="point3"/>.
			/// </para>
			/// </remarks>
			private static PointF BisectAngle(PointF point1, PointF point2, PointF point3, float magnitude)
			{
				PointF[] points = new PointF[] {point1, point3};
				using (Matrix2D rotation = new Matrix2D())
				{
					rotation.Rotate((float) (-Vector.SubtendedAngle(point1, point2, point3)/2 + 180));
					rotation.Translate(-point2.X, -point2.Y);
					rotation.TransformPoints(points);
				}

				Vector3D result = new Vector3D(points[0].X, points[0].Y, 0);
				if (FloatComparer.AreEqual(result.Magnitude, 0F, 0.01F))
					result = new Vector3D(-1, 0, 0);
				result = result/result.Magnitude*magnitude;

				return new PointF(point2.X - result.X, point2.Y - result.Y);
			}
Пример #46
0
        protected override void OnPaint(PaintEventArgs e)
        {            
            if (dirtyScreenBuf)
            {
                RenderShapefiles();
            }
            if (screenBuf != null)
            {
               // bool selecting = (_panSelectMode != PanSelectMode.Pan);
                e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                if (_panSelectMode == PanSelectMode.SelectRectangle)
                {
                    e.Graphics.DrawImage(screenBuf, e.ClipRectangle, e.ClipRectangle, GraphicsUnit.Pixel);
                    using (Pen p = new Pen(Color.Red, 1))
                    {
                        using(Brush b = new SolidBrush(Color.FromArgb(20, Color.Red)))
                        {
                            p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
                            
                            Rectangle selectRect = new Rectangle(mouseOffPt.X>=0?mouseDownPt.X:mouseDownPt.X+mouseOffPt.X,
                                mouseOffPt.Y>=0?mouseDownPt.Y:mouseDownPt.Y+mouseOffPt.Y,
                                mouseOffPt.X>=0?mouseOffPt.X:-mouseOffPt.X,
                                mouseOffPt.Y>=0?mouseOffPt.Y:-mouseOffPt.Y);
                            
                            e.Graphics.FillRectangle(b, selectRect);
                            e.Graphics.DrawRectangle(p, selectRect);
                        }
                    }
                }
                else if (_panSelectMode == PanSelectMode.SelectCircle)
                {
                    e.Graphics.DrawImage(screenBuf, e.ClipRectangle, e.ClipRectangle, GraphicsUnit.Pixel);
                    using (Pen p = new Pen(Color.Red, 1))
                    {
                        using (Brush b = new SolidBrush(Color.FromArgb(20, Color.Red)))
                        {
                            p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;

                            int radius = (int)Math.Round(Math.Sqrt(mouseOffPt.X * mouseOffPt.X + mouseOffPt.Y * mouseOffPt.Y));
                            Rectangle selectRect = new Rectangle(mouseDownPt.X -radius,
                                mouseDownPt.Y -radius,
                                radius*2,
                                radius*2);

                            //e.Graphics.FillRectangle(b, selectRect);
                            //e.Graphics.DrawRectangle(p, selectRect);
                            e.Graphics.FillEllipse(b, selectRect);
                            e.Graphics.DrawEllipse(p, selectRect);
                        }
                    }

                }
                else// if (_panSelectMode == PanSelectMode.Pan)
                {
                    //change this to only draw invalid area
                    if ((mouseOffPt.X == 0) && (mouseOffPt.Y == 0))
                    {
                        e.Graphics.DrawImage(screenBuf, e.ClipRectangle, e.ClipRectangle, GraphicsUnit.Pixel);
                    }
                    else
                    {
                        e.Graphics.DrawImage(screenBuf, mouseOffPt.X, mouseOffPt.Y);
                    }
                }
            }

            System.Drawing.Drawing2D.Matrix m = e.Graphics.Transform;
            try
            {
                System.Drawing.Drawing2D.Matrix m2 = new System.Drawing.Drawing2D.Matrix();
                m2.Translate(mouseOffPt.X, mouseOffPt.Y);
                e.Graphics.Transform = m2;
                base.OnPaint(e);
            }
            finally
            {
                e.Graphics.Transform = m;
            }
        }
Пример #47
0
        ///// <summary>
        ///// Fires the HighlightChanged event
        ///// </summary>
        ///// <param name="isHighlighted">Specifies the new boolean for whether or not this control is highlighted</param>
        //protected virtual void OnHighlightChanged(bool isHighlighted)
        //{
        //    Invalidate();
        //    if (HighlightChanged != null) HighlightChanged(this, new HighlightEventArgs(isHighlighted));
        //}

        ///// <summary>
        ///// Handles the OnMouseMove event to initialize the Highlight Changed method
        ///// </summary>
        ///// <param name="e"></param>
        //protected override void OnMouseMove(MouseEventArgs e)
        //{
        //    base.OnMouseMove(e);
        //    IsHighlighted = true;
        //}

        ///// <summary>
        ///// Overrides the base double click behavior to add the navigate functionality
        ///// </summary>
        ///// <param name="e"></param>
        //protected override void OnDoubleClick(EventArgs e)
        //{
        //    OnNavigate(_path);
        //    base.OnDoubleClick(e);
        //}

        ///// <summary>
        ///// Fires the Navigate event
        ///// </summary>
        ///// <param name="path">The string path to navigate to</param>
        //protected virtual void OnNavigate(string path)
        //{
        //    if (Navigate != null) Navigate(this, new NavigateEventArgs(path));
        //}

        /// <summary>
        /// This method instructs this item to draw itself onto the specified graphics surface.
        /// </summary>
        /// <param name="e">A PaintEventArgs that contains the Graphics object needed for drawing.</param>
        public virtual void Draw(PaintEventArgs e)
        {
            System.Drawing.Drawing2D.Matrix oldMatrix = e.Graphics.Transform;
            System.Drawing.Drawing2D.Matrix mat = new System.Drawing.Drawing2D.Matrix();
            mat.Translate(this.Bounds.Left, this.Bounds.Top);
            e.Graphics.Transform = mat;
            OnDraw(e);
            e.Graphics.Transform = oldMatrix;
        }
Пример #48
0
        private static byte[] CreatePdfWithArrayText(String directContentTj)
        {
            MemoryStream byteStream = new MemoryStream();

            Document document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, byteStream);
            document.SetPageSize(PageSize.LETTER);

            document.Open();

            PdfContentByte cb = writer.DirectContent;

            BaseFont font = BaseFont.CreateFont();

            Matrix matrix = new Matrix();
            matrix.Translate(100, 500);
            cb.Transform(matrix);
            cb.BeginText();
            cb.SetFontAndSize(font, 12);

            cb.InternalBuffer.Append(directContentTj + "\n");

            cb.EndText();

            document.Close();

            byte[] pdfBytes = byteStream.ToArray();

            return pdfBytes;

        }
Пример #49
0
            public void TestAffineTransform2D()
            {
                //Setup some affine transformation
                System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix();
                matrix.RotateAt(30, new System.Drawing.PointF(0, 0));
                matrix.Translate(-20, -20, System.Drawing.Drawing2D.MatrixOrder.Append);
                matrix.Shear(0.95f, -0.2f, System.Drawing.Drawing2D.MatrixOrder.Append);

                //Create some random sample data
                CreatingData cd = new CreatingData();
                SharpMap.Data.FeatureDataTable fdt1 =
                cd.CreatePointFeatureDataTableFromArrays(GetRandomOrdinates(80, -180, 180),
                                                         GetRandomOrdinates(80, -90, 90), null);

                //Clone random sample data and apply affine transformation on it
                SharpMap.Data.FeatureDataTable fdt2 = TransformedFeatureDataTable(matrix, fdt1);

                //Get affine transformation with LeastSquaresTransform
                SharpMap.Utilities.LeastSquaresTransform lst = new SharpMap.Utilities.LeastSquaresTransform();

                //Add at least three corresponding points
                lst.AddInputOutputPoint(
                ((SharpMap.Data.FeatureDataRow)fdt1.Rows[0]).Geometry as SharpMap.Geometries.Point,
                ((SharpMap.Data.FeatureDataRow)fdt2.Rows[0]).Geometry as SharpMap.Geometries.Point);

                lst.AddInputOutputPoint(
                ((SharpMap.Data.FeatureDataRow)fdt1.Rows[39]).Geometry as SharpMap.Geometries.Point,
                ((SharpMap.Data.FeatureDataRow)fdt2.Rows[39]).Geometry as SharpMap.Geometries.Point);

                lst.AddInputOutputPoint(
                ((SharpMap.Data.FeatureDataRow)fdt1.Rows[79]).Geometry as SharpMap.Geometries.Point,
                ((SharpMap.Data.FeatureDataRow)fdt2.Rows[79]).Geometry as SharpMap.Geometries.Point);

                /*
                //Get affine transformation calculates mean points to improve accuaracy
                //Unfortunately the result is not very good, so, since I know better I manually set these
                //mean points.
                lst.SetMeanPoints(new SharpMap.Geometries.Point(0, 0),
                              new SharpMap.Geometries.Point(matrix.OffsetX, matrix.OffsetY));
                 */

                //Create Affine
                AffineCoordinateTransformation2D at2 = new AffineCoordinateTransformation2D(lst.GetAffineTransformation());

                //Create Map
                SharpMap.Map map = new SharpMap.Map(new System.Drawing.Size(720, 360));

                //Add not transformed layer
                map.Layers.Add(new SharpMap.Layers.VectorLayer("L1",
                                                           new SharpMap.Data.Providers.GeometryFeatureProvider(fdt1)));
                ((SharpMap.Layers.VectorLayer) map.Layers[0]).Style.Symbol =
                new System.Drawing.Bitmap(@"..\..\..\DemoWinForm\Resources\flag.png");

                //Add transformed layer
                map.Layers.Add(new SharpMap.Layers.VectorLayer("L2",
                                                           new SharpMap.Data.Providers.GeometryFeatureProvider(fdt2)));
                ((SharpMap.Layers.VectorLayer) map.Layers[1]).Style.Symbol =
                new System.Drawing.Bitmap(@"..\..\..\DemoWinForm\Resources\women.png");

                //Render map
                map.ZoomToExtents();

                //Get map and save to file
                var bmp = (System.Drawing.Bitmap)map.GetMap();
                bmp.Save("affinetransform1.bmp");

                //we want to reverse the previously applied transformation.
                ((SharpMap.Layers.VectorLayer) map.Layers[1]).CoordinateTransformation = (AffineCoordinateTransformation2D)at2.Inverse();

                //Render map
                map.ZoomToExtents();

                //Get map and save to file
                bmp = (System.Drawing.Bitmap)map.GetMap();
                bmp.Save("affinetransform2.bmp");
                //Hopefully women cover flags ;-).
            }
Пример #50
0
        public static Image RotateImage(Image inputImg, double degreeAngle)
        {
            //Corners of the image
            PointF[] rotationPoints = { new PointF(0, 0),
                                        new PointF(inputImg.Width, 0),
                                        new PointF(0, inputImg.Height),
                                        new PointF(inputImg.Width, inputImg.Height)};

            //Rotate the corners
            PointMath.RotatePoints(rotationPoints, new PointF(inputImg.Width / 2.0f, inputImg.Height / 2.0f), degreeAngle);

            //Get the new bounds given from the rotation of the corners
            //(avoid clipping of the image)
            Rectangle bounds = PointMath.GetBounds(rotationPoints);

            //An empy bitmap to draw the rotated image
            Bitmap rotatedBitmap = new Bitmap(bounds.Width, bounds.Height);

            using (Graphics g = Graphics.FromImage(rotatedBitmap))
            {
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                //Transformation matrix
                System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix();
                m.RotateAt((float)degreeAngle, new PointF(inputImg.Width / 2.0f, inputImg.Height / 2.0f));
                m.Translate(-bounds.Left, -bounds.Top, System.Drawing.Drawing2D.MatrixOrder.Append); //shift to compensate for the rotation

                g.Transform = m;
                g.DrawImage(inputImg, 0, 0);
            }
            return (Image)rotatedBitmap;
        }
Пример #51
0
            public void TestMatrix()
            {
                SharpMap.Geometries.Point p = new Point(10, 10);
                var b = p.AsBinary();

                System.Drawing.Drawing2D.Matrix mat = new System.Drawing.Drawing2D.Matrix();
                mat.Rotate(30);
                mat.Translate(-20, 20);
                System.Drawing.PointF[] pts = new System.Drawing.PointF[] { new System.Drawing.PointF(50, 50) };

                mat.TransformPoints(pts);
                System.Diagnostics.Debug.WriteLine(string.Format("POINT ({0} {1})", pts[0].X, pts[0].Y));
                System.Drawing.PointF ptt = pts[0];
                System.Drawing.PointF[] ptts = new System.Drawing.PointF[] { new System.Drawing.PointF(ptt.X, ptt.Y) };
                System.Drawing.Drawing2D.Matrix inv = mat.Clone();
                inv.Invert();
                inv.TransformPoints(ptts);
                NUnit.Framework.Assert.LessOrEqual(System.Math.Abs(ptts[0].X - 50f), 0.01);
                NUnit.Framework.Assert.LessOrEqual(System.Math.Abs(ptts[0].Y - 50f), 0.01);
            }
		protected override void CalculatePreTransform(Matrix cumulativeTransform)
		{
			if (_imagePosterior != null)
			{
				// when the posterior edge of the image can be determined,
				// apply an offset in addition to user-applied translations
				// this allows the image to appear initially at (and reset to)
				// a position where the posterior ("chest wall") is aligned
				// against an edge of the client rectangle.

				// compute the posterior vector according to the adjusted parameters
				var destPosteriorVector = GetCurrentPosteriorVector(_imagePosterior, SourceWidth, AdjustedSourceHeight, RotationXY, ScaleX, ScaleY, FlipX, FlipY);

				// check if posterior direction is along client X axis
				if (Math.Abs(destPosteriorVector.X) > Math.Abs(destPosteriorVector.Y))
				{
					// compute additional horizontal translation to align posterior edge of image with client bounds
					cumulativeTransform.Translate(Math.Sign(destPosteriorVector.X)*((ClientRectangle.Width - Math.Abs(destPosteriorVector.X))/2f), 0);
				}
				else
				{
					// compute additional vertical translation to align posterior edge of image with client bounds
					cumulativeTransform.Translate(0, Math.Sign(destPosteriorVector.Y)*((ClientRectangle.Height - Math.Abs(destPosteriorVector.Y))/2f));
				}
			}
			base.CalculatePreTransform(cumulativeTransform);
		}
 public override void SetBoundingRect(System.Drawing.RectangleF bounds)
 {
     // this method hasn't been used yet
     switch (this.Shape)
     {
         case PathShape.Curve:
             throw new NotImplementedException();
         case PathShape.Ellipse:
             //m_path = new VectorPath();
             //m_path.AddEllipse(bounds);
             //break;
         case PathShape.Rectangle:
             //m_path = new VectorPath();
             //m_path.AddRectangle(bounds);
             //break;
         case PathShape.Freeform:
             RectangleF oldBounds = GetBoundingRect();
             SizeF oldSize = oldBounds.Size;
             SizeF newSize = bounds.Size;
             PointF oldCorner = oldBounds.Location;
             PointF newCorner = bounds.Location;
             System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix();
             m.Translate(-oldCorner.X, -oldCorner.Y);
             m.Scale(newSize.Width / oldSize.Width, newSize.Height / oldSize.Height);
             m.Translate(newCorner.X, newCorner.Y);
             m_path.Transform(m);
             break;
     }
 }
Пример #54
0
        /// <summary>
        /// Draws labels in a specified rectangle
        /// </summary>
        /// <param name="g">The graphics object to draw to</param>
        /// <param name="labelText">The label text to draw</param>
        /// <param name="labelBounds">The rectangle of the label</param>
        /// <param name="symb">the Label Symbolizer to use when drawing the label</param>
        private static void DrawLabel(Graphics g, string labelText, RectangleF labelBounds, ILabelSymbolizer symb)
        {
            //Sets up the brushes and such for the labeling
            Brush foreBrush = new SolidBrush(symb.FontColor);
            Font textFont = symb.GetFont();
            StringFormat format = new StringFormat();
            format.Alignment = symb.Alignment;
            Pen borderPen = new Pen(symb.BorderColor);
            Brush backBrush = new SolidBrush(symb.BackColor);
            Brush haloBrush = new SolidBrush(symb.HaloColor);
            Pen haloPen = new Pen(symb.HaloColor);
            haloPen.Width = 2;
            haloPen.Alignment = System.Drawing.Drawing2D.PenAlignment.Outset;
            Brush shadowBrush = new SolidBrush(symb.DropShadowColor);

            //Text graphics path
            System.Drawing.Drawing2D.GraphicsPath gp = new System.Drawing.Drawing2D.GraphicsPath();
            gp.AddString(labelText, textFont.FontFamily, (int)textFont.Style, textFont.SizeInPoints * 96F / 72F, labelBounds, format);

            //Draws the text outline
            if (symb.BackColorEnabled && symb.BackColor != Color.Transparent)
            {
                if (symb.FontColor == Color.Transparent)
                {
                    System.Drawing.Drawing2D.GraphicsPath backgroundGP = new System.Drawing.Drawing2D.GraphicsPath();
                    backgroundGP.AddRectangle(labelBounds);
                    backgroundGP.FillMode = System.Drawing.Drawing2D.FillMode.Alternate;
                    backgroundGP.AddPath(gp, true);
                    g.FillPath(backBrush, backgroundGP);
                    backgroundGP.Dispose();
                }
                else
                {
                    g.FillRectangle(backBrush, labelBounds);
                }
            }

            //Draws the border if its enabled
            if (symb.BorderVisible && symb.BorderColor != Color.Transparent)
                g.DrawRectangle(borderPen, labelBounds.X, labelBounds.Y, labelBounds.Width, labelBounds.Height);

            //Draws the drop shadow                      
            if (symb.DropShadowEnabled && symb.DropShadowColor != Color.Transparent)
            {
                System.Drawing.Drawing2D.Matrix gpTrans = new System.Drawing.Drawing2D.Matrix();
                gpTrans.Translate(symb.DropShadowPixelOffset.X, symb.DropShadowPixelOffset.Y);
                gp.Transform(gpTrans);
                g.FillPath(shadowBrush, gp);
                gpTrans = new System.Drawing.Drawing2D.Matrix();
                gpTrans.Translate(-symb.DropShadowPixelOffset.X, -symb.DropShadowPixelOffset.Y);
                gp.Transform(gpTrans);
            }

            //Draws the text halo
            if (symb.HaloEnabled && symb.HaloColor != Color.Transparent)
                g.DrawPath(haloPen, gp);

            //Draws the text if its not transparent
            if (symb.FontColor != Color.Transparent)
                g.FillPath(foreBrush, gp);

            //Cleans up the rest of the drawing objects
            shadowBrush.Dispose();
            borderPen.Dispose();
            foreBrush.Dispose();
            backBrush.Dispose();
            haloBrush.Dispose();
            haloPen.Dispose();
        }
Пример #55
0
        public void TestScale(float tx, float ty, float sx, float sy)
        {
            dsxy = sx;
            matrixd = new System.Drawing.Drawing2D.Matrix();//System.Drawing.Drawing2D.Matrix(1, 0, 0, -1, 0, 0);

            matrixd.Scale(sx, sy, System.Drawing.Drawing2D.MatrixOrder.Append);
            matrixd.Translate(tx, ty, System.Drawing.Drawing2D.MatrixOrder.Append);
        }
Пример #56
0
        protected override void Draw(PdfContentByte cb)
        {
            //TODO if width and height not know: what to do
            //PdfTemplate template = cb.CreateTemplate(this.width, this.height);		
            PdfTemplate template = cb.CreateTemplate(500, 500);
            //draw the list of elements on the new template
            foreach (IElement elem in this.list)
            {
                Graphic graphic = (Graphic)elem;

                if (applyCSSToElements)
                {
                    graphic.Draw(template, GetCombinedCss(graphic.GetCss(), GetCss()));
                }
                else
                {
                    graphic.Draw(template, graphic.GetCss());
                }
            }
            //add the template at the x, y position
            System.Drawing.Drawing2D.Matrix translation = new System.Drawing.Drawing2D.Matrix();
            translation.Translate(this.x, this.y);
            cb.ConcatCTM(translation);

            cb.Add(template);
        }
Пример #57
0
        public bool Render(DisplayInformation dpInfo, LayoutManager lm, bool isDesktopMode)
        {
            if( m_outputPath == string.Empty)
                return false;

            Rectangle wallRect;

            if (isDesktopMode)
            {
                wallRect = dpInfo.DesktopBounds;
            }
            else
            {
                wallRect = dpInfo.Primary.Bounds;
                wallRect.X = 0;
                wallRect.Y = 0;
            }

            //  Create the bitmap representing the wallpaper
            Bitmap bmp = new Bitmap(wallRect.Width, wallRect.Height);

            Graphics e = Graphics.FromImage(bmp);

            e.FillRectangle(Brushes.Black, 0, 0, wallRect.Width, wallRect.Height);

            foreach(KeyValuePair<int, LayoutCanvas> kvp in lm)
            {
                LayoutCanvas canvas = kvp.Value;
                Screen screen = dpInfo.Screens[kvp.Key];

                //  Get X and Y coordinates of screen in IMAGE coordinates (taking into account
                //  the shifts required to display the image properly)
                int x = (screen.X < 0) ? wallRect.Width + screen.X : screen.X;
                int y = (screen.Y < 0) ? -screen.Y : screen.Y;

                Rectangle scrBounds = new Rectangle(x, y, screen.Width, screen.Height);

                //  Fill screen background
                if (screen.Y >= 0)
                {
                    e.FillRectangle(new SolidBrush(canvas.BackgroundColour), scrBounds);
                }
                else
                {
                    Rectangle scrTop = new Rectangle(x, wallRect.Height - y, scrBounds.Width, -wallRect.Y);
                    Rectangle scrBtm = new Rectangle(x, -wallRect.Y - y, scrBounds.Width, scrBounds.Height + wallRect.Y);

                    Brush brush = new SolidBrush(canvas.BackgroundColour);

                    e.FillRectangle(brush, scrTop);
                    e.FillRectangle(brush, scrBtm);
                }

                //  Sort based on ZIndex
                LayoutObject[] clone = new LayoutObject[canvas.Count];
                canvas.CopyTo(clone);
                BubbleSort(clone);

                for( int i = 0; i < clone.Length; i++)
                {
                    LayoutObject lo = clone[i];

                    string trueSource = string.Empty;

                    if (canvas.IsShuffleEnabled)
                    {
                        trueSource = FileRandomizer.GetRandomFile(
                            Path.GetDirectoryName(lo.Source));
                    }
                    else
                    {
                        trueSource = lo.Source;
                    }

                    Rectangle loBounds = new Rectangle(lo.X + x, lo.Y + y, lo.ActualWidth, lo.ActualHeight);

                    if (scrBounds.IntersectsWith(loBounds))
                    {
                        //  Get intersecting region
                        Rectangle intRect = Rectangle.Intersect(scrBounds, loBounds);

                        //  Resized image
                        Bitmap bmpImage;

                        if (lo.IsFlippedX || lo.IsFlippedY)
                        {
                            bmpImage = new Bitmap(loBounds.Width, loBounds.Height);
                            Graphics gb = Graphics.FromImage(bmpImage);

                            System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix();

                            m.Scale((lo.IsFlippedX) ? -1 : 1, (lo.IsFlippedY) ? -1 : 1);

                            if(lo.IsFlippedX)
                                m.Translate((float)-loBounds.Width + 1, 0);

                            if (lo.IsFlippedY)
                                m.Translate(0, (float)-loBounds.Height + 1);

                            gb.Transform = m;
                            gb.DrawImage(Image.FromFile(trueSource), new Rectangle(0, 0, loBounds.Width, loBounds.Height));
                            gb.Flush();
                            gb.Dispose();
                            gb = null;
                        }
                        else
                        {
                            bmpImage= new Bitmap(Image.FromFile(trueSource), loBounds.Size);
                        }

                        //  The destination rectangle has the same width and height as the intersection rect
                        //  but we must update the coordinates
                        Rectangle destRect = intRect;

                        //  Get the image's x and y coordinates relative to the screen position
                        int ix = loBounds.X - x;
                        int iy = loBounds.Y - y;

                        //  Offset the in image coords with the image coords
                        destRect.X = (ix < 0) ? x : (x + ix);
                        destRect.Y = (iy < 0) ? y : (y + iy);

                        //  Calculate the source rectangle
                        Rectangle srcRect = intRect;

                        srcRect.X = 0;
                        srcRect.Y = 0;

                        //  If the image has negative coordinates, ie, it starts off the screen, we must
                        //  set the x to equal the portion into the image thats on the screen
                        if (ix < 0) srcRect.X = (-1 * ix);
                        if (iy < 0) srcRect.Y = (-1 * iy);

                        if (screen.Y >= 0)
                        {
                            e.DrawImage(bmpImage, destRect, srcRect, GraphicsUnit.Pixel);
                        }
                        else
                        {
                            /*

                            +----------------+
                            |xxxxxxxxxxxxxxxx|
                            |xxxxxxxxxxxxxxxx|
                            |                +----------------+
                            |                |                |
                            +----------------+                |
                                             |                |
                                             +----------------+

                            */
                            destRect.Offset(0, screen.Y);

                            Rectangle scrTop = new Rectangle(x, y + wallRect.Y, scrBounds.Width, -wallRect.Y);
                            Rectangle scrBtm = new Rectangle(x, y, scrBounds.Width, scrBounds.Height + wallRect.Y);

                            Rectangle destRectTop = Rectangle.Intersect(scrTop, destRect);
                            Rectangle destRectBtm = Rectangle.Intersect(scrBtm, destRect);

                            //  destRectBtm -> Paints ontop
                            //  destRectTop -> Paints on bottom

                            destRectTop.Y = destRect.Y + (wallRect.Height - y);
                            destRectBtm.Y = -wallRect.Y - y;

                            Rectangle srcRectTop = new Rectangle(srcRect.X, srcRect.Y, destRectTop.Width, destRectTop.Height);
                            Rectangle srcRectBtm = new Rectangle(srcRect.X, srcRect.Y + srcRectTop.Height, destRectBtm.Width, destRectBtm.Height);

                            e.DrawImage(bmpImage, destRectTop, srcRectTop, GraphicsUnit.Pixel);
                            e.DrawImage(bmpImage, destRectBtm, srcRectBtm, GraphicsUnit.Pixel);
                        }

                        bmpImage.Dispose();
                        bmpImage = null;
                    }
                }
            }

            e.Flush(System.Drawing.Drawing2D.FlushIntention.Flush);

            try
            {
                bmp.Save(m_outputPath, m_format);
            }
            catch(Exception)
            {
                e.Dispose();
                e = null;
                bmp.Dispose();
                bmp = null;

                return false;
            }

            e.Dispose();
            e = null;
            bmp.Dispose();
            bmp = null;

            GC.Collect();
            return true;
        }
Пример #58
0
        private Bitmap GetCurrentStateImage()
        {
            Bitmap bitmap = new Bitmap(this.WidthInternal, this.HeightInternal, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); // Format32bppArgb);
            bitmap.MakeTransparent();
            Graphics g = Graphics.FromImage(bitmap);

            try
            {
                System.Windows.Forms.Control cc = this.ContainerControl as System.Windows.Forms.Control;
                bool antiAlias = false;
                ItemPaintArgs pa = null;
                if (cc is ItemControl)
                {
                    antiAlias = ((ItemControl)cc).AntiAlias;
                    pa = ((ItemControl)cc).GetItemPaintArgs(g);
                }
                else if (cc is Bar)
                {
                    antiAlias = ((Bar)cc).AntiAlias;
                    pa = ((Bar)cc).GetItemPaintArgs(g);
                }
                else if (cc is ButtonX)
                {
                    antiAlias = ((ButtonX)cc).AntiAlias;
                    pa = ((ButtonX)cc).GetItemPaintArgs(g);
                }

                System.Drawing.Drawing2D.Matrix myMatrix = new System.Drawing.Drawing2D.Matrix();
                myMatrix.Translate(-this.DisplayRectangle.X, -this.DisplayRectangle.Y, System.Drawing.Drawing2D.MatrixOrder.Append);
                g.Transform = myMatrix;
                myMatrix.Dispose();
                myMatrix = null;
                if (antiAlias)
                {
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    g.TextRenderingHint = DisplayHelp.AntiAliasTextRenderingHint;
                }

                if (pa == null)
                {
                    bitmap.Dispose();
                    return null;
                }

                this.Paint(pa);
            }
            finally
            {
                g.Dispose();
            }
            return bitmap;
        }
        /// <summary>
        /// On Paint only paints the specified clip rectangle, but paints
        /// it from the page buffer.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPaint(PaintEventArgs e)
        {

            Rectangle clip = e.ClipRectangle;
            if (clip.IsEmpty) clip = ClientRectangle;
            if (IsInitialized == false || _buffer == null)
            {
                Initialize(); // redraw the entire page buffer if necessary
            }

            Bitmap buffer = new Bitmap(clip.Width, clip.Height);
            Graphics g = Graphics.FromImage(buffer);
            System.Drawing.Drawing2D.Matrix mat = new System.Drawing.Drawing2D.Matrix();
            mat.Translate(-clip.X, -clip.Y); // draw in "client" coordinates
            g.Transform = mat;
            
            OnDraw(new PaintEventArgs(g, clip)); // draw content to the small temporary buffer.

            g.Dispose();
            e.Graphics.DrawImage(buffer, clip); // draw from our small, temporary buffer to the screen
            buffer.Dispose();
        }
Пример #60
0
        private static byte[] CreatePdfWithRotatedText(String text1, String text2, float rotation, bool moveTextToNextLine, float moveTextDelta)
        {

            MemoryStream byteStream = new MemoryStream();

            Document document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, byteStream);
            document.SetPageSize(PageSize.LETTER);

            document.Open();

            PdfContentByte cb = writer.DirectContent;

            BaseFont font = BaseFont.CreateFont();

            float x = document.PageSize.Width / 2;
            float y = document.PageSize.Height / 2;

            Matrix matrix = new Matrix();
            matrix.Translate(x, y);
            cb.Transform(matrix);

            cb.MoveTo(-10, 0);
            cb.LineTo(10, 0);
            cb.MoveTo(0, -10);
            cb.LineTo(0, 10);
            cb.Stroke();

            cb.BeginText();
            cb.SetFontAndSize(font, 12);
            matrix = new Matrix();
            matrix.Rotate(rotation);
            cb.Transform(matrix);
            cb.ShowText(text1);
            if (moveTextToNextLine)
                cb.MoveText(0, moveTextDelta);
            else
            {
                matrix = new Matrix();
                matrix.Translate(moveTextDelta, 0);
                cb.Transform(matrix);
            }
            cb.ShowText(text2);
            cb.EndText();

            document.Close();

            byte[] pdfBytes = byteStream.ToArray();

            return pdfBytes;
        }