public PDFTransformationMatrix(float offsetX, float offsetY, float angle, float scaleX, float scaleY) : this() { _matrix.Translate(offsetX, offsetY); _matrix.Rotate(angle); _matrix.Scale(scaleX, scaleY); }
/// <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(); }
void Command_Image_Rotate(ImageRotateDialog.Result result) { var variables = GetVariables(); var angle = new NEExpression(result.AngleExpression).Evaluate <float>(variables, "deg"); var bitmap = GetBitmap(); var path = new System.Drawing.Drawing2D.GraphicsPath(); path.AddRectangle(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height)); var matrix = new System.Drawing.Drawing2D.Matrix(); matrix.Rotate(angle); var rect = path.GetBounds(matrix); var resultBitmap = new System.Drawing.Bitmap((int)rect.Width, (int)rect.Height, bitmap.PixelFormat); using (var g = System.Drawing.Graphics.FromImage(resultBitmap)) { g.TranslateTransform(-rect.X, -rect.Y); g.RotateTransform(angle); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear; g.DrawImageUnscaled(bitmap, 0, 0); } Replace(new List <Range> { FullRange }, new List <string> { Coder.BitmapToString(resultBitmap) }); SetSelections(new List <Range> { BeginRange }); }
/// <summary> Rotates the current transformation by the given angle. /// /// </summary> /// <param name="angle">rotation in degrees. /// </param> public virtual void Rotate(double angle) { System.Drawing.Drawing2D.Matrix temp_Matrix; temp_Matrix = new System.Drawing.Drawing2D.Matrix(); temp_Matrix.Rotate((float)(SupportClass.DegreesToRadians(angle) * (180 / System.Math.PI))); transform(temp_Matrix); }
//UPGRADE_NOTE: ref keyword was added to struct-type parameters. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1303_3"' public override void getBounds(System.Drawing.Drawing2D.Matrix transform, ref System.Drawing.Rectangle r, ref System.Drawing.PointF position) { System.Drawing.Rectangle a = new System.Drawing.Rectangle(); double x, y; x = (double)position.X - System.Math.Cos(SupportClass.DegreesToRadians(startAngle)) * xRadius; y = (double)position.Y - System.Math.Sin(SupportClass.DegreesToRadians(startAngle)) * yRadius; //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1042_3"' a.X = (int)(x - xRadius); //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1042_3"' a.Y = (int)(y - yRadius); //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1042_3"' a.Width = (int)System.Math.Ceiling(x + xRadius) - a.X; //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1042_3"' a.Height = (int)System.Math.Ceiling(y + yRadius) - a.Y; System.Drawing.Drawing2D.Matrix temp_Matrix; temp_Matrix = new System.Drawing.Drawing2D.Matrix(); temp_Matrix.Rotate((float)(rotation * (180 / System.Math.PI))); //UPGRADE_NOTE: ref keyword was added to struct-type parameters. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1303_3"' a = Util.transform(Util.multiply(transform, temp_Matrix), ref a); //UPGRADE_NOTE: ref keyword was added to struct-type parameters. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1303_3"' Util.combine(ref r, ref a); //UPGRADE_NOTE: ref keyword was added to struct-type parameters. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1303_3"' System.Drawing.PointF endPoint = calcPoint(1.0, ref position); position.X = (float)endPoint.X; position.Y = (float)endPoint.Y; }
public System.Drawing.Bitmap KiRotate(System.Drawing.Bitmap bmp, float angle) { int w = bmp.Width + 2; int h = bmp.Height + 2; System.Drawing.Imaging.PixelFormat pf; pf = bmp.PixelFormat; System.Drawing.Bitmap tmp = new System.Drawing.Bitmap(w, h, pf); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(tmp); //g.Clear(bkColor); g.DrawImageUnscaled(bmp, 1, 1); g.Dispose(); System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath(); path.AddRectangle(new System.Drawing.RectangleF(0f, 0f, w, h)); System.Drawing.Drawing2D.Matrix mtrx = new System.Drawing.Drawing2D.Matrix(); mtrx.Rotate(angle); System.Drawing.RectangleF rct = path.GetBounds(mtrx); System.Drawing.Bitmap dst = new System.Drawing.Bitmap((int)rct.Width, (int)rct.Height, pf); g = System.Drawing.Graphics.FromImage(dst); //g.Clear(bkColor); g.TranslateTransform(-rct.X, -rct.Y); g.RotateTransform(angle); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear; g.DrawImageUnscaled(tmp, 0, 0); g.Dispose(); tmp.Dispose(); return(dst); }
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); }
public IEnumerable <System.Drawing.Rectangle> iterPreventRects() { var transform = new System.Drawing.Drawing2D.Matrix(); var pts = new System.Drawing.Point[1]; int circleCount = 16; float angleDelta = 360 / circleCount; float angle = 0; for (int i = 0; i < circleCount; ++i) { transform.Reset(); transform.Rotate(angle); pts[0] = new System.Drawing.Point(0, 96); transform.TransformPoints(pts); var pt = pts[0]; var hitRect = new System.Drawing.Rectangle(this.x + pt.X - 48, this.y + pt.Y - 48, 96, 96); // bool isCollision = _gamePlay.scene.hitTestCollision(snake.headPreventCollisionRect); //Console.WriteLine("{0} Prevent angle={1} hit={2}", snake, angle, isCollision); if (_headPreventCollisionRect.IntersectsWith(hitRect) == false) { yield return(hitRect); } angle += angleDelta; } }
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); }
/// <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); } } }
private byte[] CreatePdfWithRotatedXObject(String xobjectText) { MemoryStream baos = new MemoryStream(); Document doc = new Document(); PdfWriter writer = PdfWriter.GetInstance(doc, baos); writer.CompressionLevel = 0; doc.Open(); doc.Add(new Paragraph("A")); doc.Add(new Paragraph("B")); bool rotate = true; PdfTemplate template = writer.DirectContent.CreateTemplate(20, 100); template.SetColorStroke(BaseColor.GREEN); template.Rectangle(0, 0, template.Width, template.Height); template.Stroke(); Matrix matrix = new Matrix(); if (rotate) { matrix.Translate(0, template.Height); matrix.Rotate(-90); } template.Transform(matrix); template.BeginText(); template.SetFontAndSize(BaseFont.CreateFont(), 12); if (rotate) { template.MoveText(0, template.Width - 12); } else { template.MoveText(0, template.Height - 12); } template.ShowText(xobjectText); template.EndText(); Image xobjectImage = Image.GetInstance(template); if (rotate) { xobjectImage.RotationDegrees = 90; } doc.Add(xobjectImage); doc.Add(new Paragraph("C")); doc.Close(); return(baos.ToArray()); }
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); }
private static Vector3D GetCurrentPosteriorVector(Vector3D imagePosterior, int sourceWidth, float adjustedSourceHeight, int rotation, float scaleX, float scaleY, bool flipX, bool flipY) { // figure out where the posterior direction went using (var transform = new Matrix()) { var points = new[] { new PointF(sourceWidth * imagePosterior.X, adjustedSourceHeight * imagePosterior.Y) }; transform.Rotate(rotation); transform.Scale(scaleX * (flipY ? -1 : 1), scaleY * (flipX ? -1 : 1)); transform.TransformPoints(points); return(new Vector3D(points[0].X, points[0].Y, 0)); } }
private System.Drawing.PointF _transRotPt(float angle, System.Drawing.PointF pt) { var trans1 = new System.Drawing.Drawing2D.Matrix(); trans1.Rotate(angle); var pts1 = new System.Drawing.PointF[] { pt }; trans1.TransformPoints(pts1); return(pts1[0]); }
private void _updateRotTransform() { _rotTransform = new System.Drawing.Drawing2D.Matrix(); _rotTransform.Rotate(_head.rotation); var pts = new System.Drawing.PointF[] { new System.Drawing.PointF(0, _moveSpeedValue) }; _rotTransform.TransformPoints(pts); var pt = pts[0]; _speedDelta.X = pt.X; _speedDelta.Y = pt.Y; }
/// <summary> /// Prepend to this <see cref="PMatrix"/> object a clockwise rotation, around the origin /// and by the specified angle. /// <see cref="PMatrix"/> object. /// </summary> /// <param name="theta">The angle of the rotation, in degrees.</param> /// <remarks> /// This value will be applied to the current rotation value of the matrix. This is not /// the same as setting the <see cref="PMatrix.Rotation"/> directly. /// </remarks> internal static Matrix RotateBy(Matrix matrix, float theta) { Matrix tempMatrix = Matrix.Identity; System.Drawing.Drawing2D.Matrix drawMatrix = new System.Drawing.Drawing2D.Matrix( matrix.M11, matrix.M12, matrix.M21, matrix.M22, matrix.M41, matrix.M42); drawMatrix.Rotate(theta); tempMatrix = SetElements(drawMatrix); return(tempMatrix); //MatrixExtensions.Rotate(ref matrix, theta, out outMatrix); }
private void _joystick_movementEvent(JoystickEvent evt) { //Console.WriteLine("_joystick_movementEvent {0}", evt); if (_player == null) return; var transform = new System.Drawing.Drawing2D.Matrix(); transform.Rotate(evt.angle); var pts = new System.Drawing.PointF[] { new PointF(0, 64) }; transform.TransformPoints(pts); var pt2 = pts[0]; //Console.WriteLine("_joystick_movementEvent angle={0} pt2={1}", evt.angle, pt2); _player.updateRotationWithRelatedPoint(pt2); _joystickDebugSprite.x = _player.x + (int)pt2.X; _joystickDebugSprite.y = _player.y + (int)pt2.Y; }
private Bitmap Rotate(Bitmap image, float angle) { Bitmap bmp = new Bitmap(image.Width, image.Height); var w = (image.Width & 1) == 0 ? image.Width + 1 : image.Width; var h = (image.Height & 1) == 0 ? image.Height + 1 : image.Height; //центр изображения var center = new System.Drawing.Point(w / 2, h / 2); //Границы изображения var rect = new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height); using (var m = new System.Drawing.Drawing2D.Matrix()) { System.Drawing.Point[] pts = new System.Drawing.Point[1]; m.Translate(center.X, center.Y); m.Rotate(-angle); //m.Invert(); for (int x = 0; x < image.Width; x++) { for (int y = 0; y < image.Height; y++) { //Вектор к пикселу pts[0] = new System.Drawing.Point(x - center.X, y - center.Y); m.TransformPoints(pts); if (!rect.Contains(pts[0])) { continue; } //bmp.SetPixel(pts[0].X, pts[0].Y, image.GetPixel(x, y)); bmp.SetPixel(x, y, image.GetPixel(pts[0].X, pts[0].Y)); } } for (int x = 0; x < bmp.Width; x++) { for (int y = 0; y < bmp.Height; y++) { if (bmp.GetPixel(x, y).A == 0) { bmp.SetPixel(x, y, System.Drawing.Color.White); } } } } return(bmp); }
/// <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)); }
public void TestMatrix() { var p = new NetTopologySuite.Geometries.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); }
virtual protected void UpdateText() { SizeF oldDimension = Dimension; PointF oldLocation = Location; float oldRotation = Rotation; Geometric.Reset(); Geometric.AddString(_displayedText, _font.FontFamily, (int)_font.Style, _font.Size, Geometric.GetBounds(), _stringFormat); System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix(); matrix.Rotate(_degree); Geometric.Transform(matrix); if (_degree != oldRotation) { base.Rotation = _degree; } base.Dimension = oldDimension; base.Location = oldLocation; }
static private void PlaceBarcode(PdfStamper stamper, Barcode barcode, int page, float left, float top, float width, float rotateDegrees = 0, float barHeight = 0, bool displayText = true, bool withBorder = true) { // Установим дополнительные параметры if (barHeight > 0) { barcode.BarHeight = barHeight; // Высота одной полоски } if (displayText == false) { barcode.Font = null; // no text } // barcode.X = 5; // длина 1-й полоски // barcode.Size = 8; // размер шрифта PdfContentByte over = stamper.GetOverContent(page); PdfTemplate template = CreateBarcodeTemplate(over, barcode, opaque: true, withBorder: true); // Поместим в нужное место документа. // Трансформации применяются в обратном порядке. // var matrix = new System.Drawing.Drawing2D.Matrix(); float scale = width / barcode.BarcodeSize.Width; // Сдвинем штрих код на свое место matrix.Translate(left, top); // Повернем штрихкод как текст повернут matrix.Rotate(rotateDegrees); // Отмасштабируем штрихкод чтобы вписать в п/у текста matrix.Scale(scale, scale); // Сдвинем штрих на величину высоты, чтобы поворот происходил вокруг верхней левой точки, а не вокруг нижней левой. matrix.Translate(0, -barcode.BarcodeSize.Height); // Применим шаблон и преобразования float[] elements = matrix.Elements; over.AddTemplate(template, elements[0], elements[1], elements[2], elements[3], elements[4], elements[5]); }
private void test_Paint(object sender, PaintEventArgs e) { e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; int radius = mSensitivityOfTest / 2; if (doingLine) { e.Graphics.FillEllipse(Brushes.Red, this.Width * 1 / 8, this.Height * 5 / 8, mSensitivityOfTest, mSensitivityOfTest); e.Graphics.FillEllipse(Brushes.Black, this.Width * 1 / 8 + radius - 3, this.Height * 5 / 8 + radius - 3, 6, 6); } else if (doingRectangle) { e.Graphics.FillEllipse(Brushes.Red, this.Width * 1 / 4, this.Height * 1 / 4, mSensitivityOfTest, mSensitivityOfTest); e.Graphics.FillEllipse(Brushes.Black, this.Width * 1 / 4 + radius - 3, this.Height * 1 / 4 + radius - 3, 6, 6); } else if (beforDoElipse) { System.Drawing.Drawing2D.Matrix matrix2 = new System.Drawing.Drawing2D.Matrix(); matrix2.Rotate(0, System.Drawing.Drawing2D.MatrixOrder.Append); matrix2.Translate(this.ClientSize.Width / 2, this.ClientSize.Height / 2, System.Drawing.Drawing2D.MatrixOrder.Append); e.Graphics.Transform = matrix2; e.Graphics.FillEllipse(Brushes.Red, -300, -300, mSensitivityOfTest, mSensitivityOfTest); e.Graphics.FillEllipse(Brushes.Black, -300 + radius - 3, -300 + radius - 3, 6, 6); if (!goExit) { bufferedGraphics.Render(Graphics.FromHwnd(this.Handle)); } } else if (beforDoingText) { e.Graphics.FillRectangle(Brushes.Red, this.Width / 8 + 5, this.Height / 8 + 25, mSensitivityOfTest, mSensitivityOfTest); e.Graphics.FillEllipse(Brushes.Black, (int)(this.Width / 8 + 5 + radius - 3), (int)(this.Height / 8 + 25 + radius - 3), 6, 6); } }
private void _onMouseMove(System.Drawing.Point pt2) { if (_isPress) { var pt1 = new System.Drawing.Point(_innerCircleSprite.x, _innerCircleSprite.y); float dist = (float)(Math.Sqrt(Math.Pow(pt2.X - pt1.X, 2) + Math.Pow(pt2.Y - pt1.Y, 2))); float angle = (float)(Math.Atan2(pt2.Y - pt1.Y, pt2.X - pt1.X) * 180.0f / Math.PI) - 90; if (dist > 64) { dist = 64; } var transform = new System.Drawing.Drawing2D.Matrix(); transform.Rotate(angle); var pts = new System.Drawing.PointF[] { new System.Drawing.PointF(0, dist) }; transform.TransformPoints(pts); var pt = pts[0]; _pointSprite.x = (int)pt.X; _pointSprite.y = (int)pt.Y; //Console.WriteLine("JoystickSprite_mouseMove angle={0} dist={1} evt={2}", angle, dist, evt); _lastAngle = angle; _isTrigger = true; if (movementEvent != null) { movementEvent(new JoystickEvent() { angle = angle }); } } }
private PointF ConvertInvariantToDestination(PointF invariantPoint) { PointF xVector = new PointF(100, 0); SizeF xVectorTransformed = base.SpatialTransform.ConvertToDestination(new SizeF(xVector)); //figure out where the source x-axis went in destination int rotation = (int)Math.Round(Vector.SubtendedAngle(xVectorTransformed.ToPointF(), PointF.Empty, xVector)); if (rotation < 0) { rotation += 360; } Matrix m = new Matrix(); m.Rotate(rotation); PointF[] pt = { invariantPoint }; m.TransformPoints(pt); m.Dispose(); return(new PointF(base.Location.X + pt[0].X, base.Location.Y + pt[0].Y)); }
virtual protected void UpdateText() { //var eee = Geometric.GetBounds(); SizeF oldDimension = Dimension; PointF oldLocation = Location; float oldRotation = Rotation; Geometric.Reset(); // Rectangle WFTitle = new Rectangle(0, 0, bmp.Width, bmp.Height); // Geometric.AddString(_displayedText, _font.FontFamily, (int)_font.Style, _font.Size, Geometric.GetBounds(), _stringFormat); //Geometric.AddString(_displayedText, this.Font.FontFamily, (int)this.Font.Style, this.Font.Size, Geometric.GetBounds(), _stringFormat); Geometric.AddString(_displayedText, this.Font.FontFamily, (int)this.Font.Style, this.Font.Size, new Point(0, 0), _stringFormat); System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix(); matrix.Rotate(_degree); Geometric.Transform(matrix); if (_degree != oldRotation) { base.Rotation = _degree; } base.Dimension = oldDimension; base.Location = oldLocation; }
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); }
/// <summary> /// Indicates whether a given point is on this link. /// </summary> /// <param name="x">X coordinate of the given point.</param> /// <param name="y">Y coordinate of the given point.</param> /// <param name="rgObjs">GOM object collection.</param> /// <returns>Whether a given point is on this link.</returns> public bool IsPointOnLink(float x, float y, GOM_Objects rgObjs) { switch (m_linkingStyle) { case GOM_Linking_Style.Line: { System.Drawing.Drawing2D.Matrix matrix; System.Drawing.PointF[] rgPts; System.Drawing.PointF startPt, endPt; startPt = StartPointInCanvas(rgObjs); endPt = EndPointInCanvas(rgObjs); rgPts = new System.Drawing.PointF[2]; rgPts[0].X = endPt.X; rgPts[0].Y = endPt.Y; rgPts[1].X = x; rgPts[1].Y = y; matrix = new System.Drawing.Drawing2D.Matrix(); matrix.Translate(-startPt.X, -startPt.Y); matrix.TransformPoints(rgPts); float angle = (float)(System.Math.Atan2(endPt.Y - startPt.Y, endPt.X - startPt.X) / System.Math.PI) * 180; matrix.Reset(); matrix.Rotate(-angle); matrix.TransformPoints(rgPts); if ((Math.Abs(rgPts[1].Y) < 2) && (-2 < rgPts[1].X) && (rgPts[1].X < rgPts[0].X + 2)) { return true; } break; } case GOM_Linking_Style.Polyline: { System.Drawing.Drawing2D.Matrix matrix; System.Drawing.PointF[] rgPts, rgAllPts; System.Drawing.PointF startPt, endPt; startPt = StartPointInCanvas(rgObjs); endPt = EndPointInCanvas(rgObjs); rgPts = new System.Drawing.PointF[2]; rgAllPts = new System.Drawing.PointF[m_keyPts.Count+2]; rgAllPts[0].X = startPt.X; rgAllPts[0].Y = startPt.Y; for(int i=0; i<m_keyPts.Count; i++) { rgAllPts[1+i].X = m_keyPts[i].x; rgAllPts[1+i].Y = m_keyPts[i].y; } rgAllPts[rgAllPts.Length-1].X = endPt.X; rgAllPts[rgAllPts.Length-1].Y = endPt.Y; for(int i=0; i<(rgAllPts.Length-1); i++) { rgPts[0].X = rgAllPts[i+1].X; rgPts[0].Y = rgAllPts[i+1].Y; rgPts[1].X = x; rgPts[1].Y = y; matrix = new System.Drawing.Drawing2D.Matrix(); matrix.Translate(-rgAllPts[i].X, -rgAllPts[i].Y); matrix.TransformPoints(rgPts); float angle = (float)(System.Math.Atan2(rgAllPts[i+1].Y - rgAllPts[i].Y, rgAllPts[i+1].X - rgAllPts[i].X) / System.Math.PI) * 180; matrix.Reset(); matrix.Rotate(-angle); matrix.TransformPoints(rgPts); if ((Math.Abs(rgPts[1].Y) < 2) && (-2 < rgPts[1].X) && (rgPts[1].X < rgPts[0].X + 2)) { return true; } } break; } case GOM_Linking_Style.Curve: { break; } default: System.Diagnostics.Debug.Assert(false, "Unknown link style."); break; } return false; }
/// <summary> /// Add a key point into this polyline link. /// </summary> /// <param name="x">X coordinate of the key point.</param> /// <param name="y">Y coordinate of the key point.</param> /// <param name="rgObjs">GOM object collection.</param> public void AddKeyPoint(float x, float y, GOM_Objects rgObjs) { if ( m_linkingStyle != GOM_Linking_Style.Polyline ) { return; } System.Drawing.Drawing2D.Matrix matrix; System.Drawing.PointF[] rgPts, rgAllPts; System.Drawing.PointF startPt, endPt; startPt = StartPointInCanvas(rgObjs); endPt = EndPointInCanvas(rgObjs); rgPts = new System.Drawing.PointF[2]; rgAllPts = new System.Drawing.PointF[m_keyPts.Count+2]; rgAllPts[0].X = startPt.X; rgAllPts[0].Y = startPt.Y; for(int i=0; i<m_keyPts.Count; i++) { rgAllPts[1+i].X = m_keyPts[i].x; rgAllPts[1+i].Y = m_keyPts[i].y; } rgAllPts[rgAllPts.Length-1].X = endPt.X; rgAllPts[rgAllPts.Length-1].Y = endPt.Y; for(int i=0; i<(rgAllPts.Length-1); i++) { rgPts[0].X = rgAllPts[i+1].X; rgPts[0].Y = rgAllPts[i+1].Y; rgPts[1].X = x; rgPts[1].Y = y; matrix = new System.Drawing.Drawing2D.Matrix(); matrix.Translate(-rgAllPts[i].X, -rgAllPts[i].Y); matrix.TransformPoints(rgPts); float angle = (float)(System.Math.Atan2(rgAllPts[i+1].Y - rgAllPts[i].Y, rgAllPts[i+1].X - rgAllPts[i].X) / System.Math.PI) * 180; matrix.Reset(); matrix.Rotate(-angle); matrix.TransformPoints(rgPts); if ((Math.Abs(rgPts[1].Y) < 2) && (-2 < rgPts[1].X) && (rgPts[1].X < rgPts[0].X + 2)) { GOM_Point point = new GOM_Point(); point.x = x; point.y = y; m_keyPts.Insert(i, point); return; } } }
public System.Drawing.PointF PointToObject(System.Drawing.PointF pt) { System.Drawing.Drawing2D.Matrix matrix; System.Drawing.RectangleF rc; System.Drawing.PointF[] rgPts; rc = this.BoundingBox; rgPts = new System.Drawing.PointF[1]; rgPts[0].X = pt.X; rgPts[0].Y = pt.Y; matrix = new System.Drawing.Drawing2D.Matrix(); matrix.Translate(-this.xOffset, -this.yOffset); matrix.TransformPoints(rgPts); matrix.Reset(); matrix.Translate(-(rc.Left + rc.Right) / 2, -(rc.Top + rc.Bottom) / 2); matrix.TransformPoints(rgPts); matrix.Reset(); matrix.Rotate(-this.rotation); matrix.TransformPoints(rgPts); matrix.Reset(); matrix.Translate((rc.Left + rc.Right) / 2, (rc.Top + rc.Bottom) / 2); matrix.TransformPoints(rgPts); return rgPts[0]; }
protected override void OnCellPainting(System.Windows.Forms.DataGridViewCellPaintingEventArgs e) { if (e.ColumnIndex >= 0 && e.RowIndex == -1) { string text = this.Columns[e.ColumnIndex].HeaderText; //Getting the width and height of the text, which we are going to write double columnTextWidth = e.Graphics.MeasureString(text, e.CellStyle.Font).Width; double columnTextHeight = e.Graphics.MeasureString(text, e.CellStyle.Font).Height; // Erase the cell. using (System.Drawing.Brush backColorBrush = new System.Drawing.SolidBrush(e.CellStyle.BackColor)) { e.Graphics.FillRectangle(backColorBrush, e.CellBounds); } // only need 1 bottom line... e.Graphics.DrawLine(System.Drawing.Pens.DarkGray, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right, e.CellBounds.Bottom - 1); // two top lines... e.Graphics.DrawLine(System.Drawing.Pens.DarkGray, e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Right, e.CellBounds.Top); e.Graphics.DrawLine(System.Drawing.Pens.White, e.CellBounds.Left, e.CellBounds.Top + 1, e.CellBounds.Right, e.CellBounds.Top + 1); // right line... e.Graphics.DrawLine(System.Drawing.Pens.DarkGray, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom); // left line... e.Graphics.DrawLine(System.Drawing.Pens.White, e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Left, e.CellBounds.Bottom); //For rotation double angle = (_rotationAngle / 180) * System.Math.PI; double hSin = columnTextHeight * System.Math.Sin(angle); double wCos = columnTextWidth * System.Math.Cos(angle); double hCos = columnTextHeight * System.Math.Cos(angle); double wSin = columnTextWidth * System.Math.Sin(angle); double rotatedWidth = hSin - wCos; double rotatedHeight = hCos - wSin; double dx = (e.CellBounds.Width + hSin - wCos) / 2; double dy = (e.CellBounds.Height - hCos - wSin) / 2; this.Columns[e.ColumnIndex].Width = ( int )System.Math.Abs(rotatedWidth) + 10; int newColHeight = ( int )System.Math.Abs(rotatedHeight) + 10; if (this.ColumnHeadersHeight < newColHeight) { this.ColumnHeadersHeight = newColHeight; } System.Drawing.Drawing2D.Matrix mx = new System.Drawing.Drawing2D.Matrix(); mx.Rotate(( float )_rotationAngle, System.Drawing.Drawing2D.MatrixOrder.Append); float heightOffset = e.CellBounds.Y + 10; mx.Translate(( float )(dx + e.CellBounds.X), heightOffset, System.Drawing.Drawing2D.MatrixOrder.Append); e.Graphics.Transform = mx; e.Graphics.DrawString(text, e.CellStyle.Font, System.Drawing.Brushes.Black, 0, 0, System.Drawing.StringFormat.GenericTypographic); e.Graphics.ResetTransform(); e.Handled = true; } else { base.OnCellPainting(e); } }
private void HardFit() { /* * Rotate the rectangle so that top-left is centered at the top with bot-right at the bottom center. This angle is BaseTheta * Find the min/max x/y * Use those and find the efficiency of that ellipse * Rotate by PI/2/ANGLETRYCOUNT for PI/2 rad's (90 degs), running this same algorithm for each rotation * Use the most efficient, using -(BaseTheta+Theta) as the rotation of the ellipse */ PointF[] Pts = (PointF[])mImgSec.PixelsUsed().SelectMany(p => new PointF[]{new PointF((float)p.X, (float)p.Y)}); System.Drawing.Drawing2D.Matrix BaseRotator = new System.Drawing.Drawing2D.Matrix(), StepRotate = new System.Drawing.Drawing2D.Matrix(); // |\ = ATan(Width/Height) so |\ | // | \ | \ | // | \ | \ | // |___\ |___\| = -Atan(W/H) float BaseTheta = (float)(-Math.Atan((double)mImgSec.Width / (double)mImgSec.Height)); BaseRotator.Rotate(BaseTheta); StepRotate.Rotate((float)Math.PI / 2f / (float)ANGLETRYCOUNT); BaseRotator.TransformPoints(Pts); double BestFit = 0d,temp; int BestChoice = -1; SizeF BestDim = new SizeF(),tempDim; for(int i = 0; i < ANGLETRYCOUNT - 1; i++, StepRotate.TransformPoints(Pts)) { if((temp = GetFit(Pts, out tempDim)) > BestFit) {BestChoice = i; BestFit = temp;BestDim = tempDim;} } mRotation = -(BaseTheta+BestChoice*Math.PI / 2d / (double)ANGLETRYCOUNT); mEllWidth = BestDim.Width; mEllHeight = BestDim.Height; return; }
private static Vector3D GetCurrentPosteriorVector(Vector3D imagePosterior, int sourceWidth, float adjustedSourceHeight, int rotation, float scaleX, float scaleY, bool flipX, bool flipY) { // figure out where the posterior direction went using (var transform = new Matrix()) { var points = new[] {new PointF(sourceWidth*imagePosterior.X, adjustedSourceHeight*imagePosterior.Y)}; transform.Rotate(rotation); transform.Scale(scaleX*(flipY ? -1 : 1), scaleY*(flipX ? -1 : 1)); transform.TransformPoints(points); return new Vector3D(points[0].X, points[0].Y, 0); } }
// draw Elipse-------------------------------------------------------------------------------------------------------------- private void OnTimerDrwElipse() { Graphics g = bufferedGraphics.Graphics; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; int radius = mSensitivityOfTest / 2; // for circle we need a 360' angle if (angle > 359) { for (int i = 0; i <= 359; i++) { System.Drawing.Drawing2D.Matrix matrix2 = new System.Drawing.Drawing2D.Matrix(); matrix2.Rotate(i, System.Drawing.Drawing2D.MatrixOrder.Append); matrix2.Translate(this.ClientSize.Width / 2, this.ClientSize.Height / 2, System.Drawing.Drawing2D.MatrixOrder.Append); g.Transform = matrix2; g.FillEllipse(Brushes.Yellow, -300, -300, 10, 10); if (!goExit) { bufferedGraphics.Render(Graphics.FromHwnd(this.Handle)); } } angle = 0; foreach (Point p in gazePointListForElips) { g.FillEllipse(Brushes.DeepSkyBlue, p.X - this.ClientSize.Width / 2 - 5, p.Y - this.ClientSize.Height / 2 - 5, 10, 10); if (!goExit) { bufferedGraphics.Render(Graphics.FromHwnd(this.Handle)); } angle++; } // Find the True and False gaze points according to shapes coordinate /* for (int i = 0; i < gazePointListForElips.Count; i++) * { * int gazeX = gazePointListForElips[i].X; * int gazeY = gazePointListForElips[i].Y; * * int shapeX = shapPointListForElips[i].X; * int shapeY = shapPointListForElips[i].Y; * * g.FillEllipse(Brushes.Blue, gazeX - this.ClientSize.Width / 2 - 5-radius, gazeY - this.ClientSize.Height / 2 - 5- radius, 10, 10); * if (!goExit) * bufferedGraphics.Render(Graphics.FromHwnd(this.Handle)); * * /* //true gaze points * if (Math.Abs(gazeX - shapeX) <= mSensitivityOfTest && Math.Abs(gazeY - shapeY) <= mSensitivityOfTest) * { * ElipsTruePoints++; * g.FillEllipse(Brushes.Green, gazeX - this.ClientSize.Width / 2 - 5, gazeY - this.ClientSize.Height / 2 - 5, 10, 10); * if (!goExit) * bufferedGraphics.Render(Graphics.FromHwnd(this.Handle)); * } * * //false gaze points * else * { * ElipsFalsePoints++; * g.FillEllipse(Brushes.Red, gazeX - this.ClientSize.Width / 2 - 5, gazeY - this.ClientSize.Height / 2 - 5, 10, 10); * if (!goExit) * bufferedGraphics.Render(Graphics.FromHwnd(this.Handle)); * } * * }*/ timer.Stop(); //Save the Image finishTesting = true; saveTheTestingImage("Elipse-Test", gazePointListForElips, shapPointListForElips); g.Clear(Color.Black); doingElipse = false; // finishTesting = true; } // g.Clear(Color.Black); if (angle <= 359 && angle != 0) { /* * X := originX + cos(angle)*radius; * Y := originY + sin(angle)*radius; * (X, Y) is the center of your circle. radius is its radius * */ int x = (int)(this.Width / 2 + Math.Cos(angle) * 300) - this.ClientSize.Width / 2; int y = (int)(this.Height / 2 + Math.Sin(angle) * 300) - this.ClientSize.Height / 2; System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix(); matrix.Rotate(angle, System.Drawing.Drawing2D.MatrixOrder.Append); matrix.Translate(this.ClientSize.Width / 2, this.ClientSize.Height / 2, System.Drawing.Drawing2D.MatrixOrder.Append); g.Transform = matrix; g.FillEllipse(Brushes.Red, -300, -300, mSensitivityOfTest, mSensitivityOfTest); g.FillEllipse(Brushes.Black, -300 + radius - 3, -300 + radius - 3, 6, 6); //adding to list gazePointListForElips.Add(getGazePoint()); shapPointListForElips.Add(new Point(x, y)); if (!goExit) { bufferedGraphics.Render(Graphics.FromHwnd(this.Handle)); } g.Clear(Color.Black); } angle++; //clearScreen //this.Close(); }
/// <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); }
private PointF ConvertInvariantToDestination(PointF invariantPoint) { PointF xVector = new PointF(100, 0); SizeF xVectorTransformed = base.SpatialTransform.ConvertToDestination(new SizeF(xVector)); //figure out where the source x-axis went in destination int rotation = (int)Math.Round(Vector.SubtendedAngle(xVectorTransformed.ToPointF(), PointF.Empty, xVector)); if (rotation < 0) rotation += 360; Matrix m = new Matrix(); m.Rotate(rotation); PointF[] pt = { invariantPoint }; m.TransformPoints(pt); m.Dispose(); return new PointF(base.Location.X + pt[0].X, base.Location.Y + pt[0].Y); }
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()); } }
private void DrawFillPattern(Graphics gfx, double width, double height) { // verify fill pattern var fillPattern = FillPattern; if (fillPattern == null) { return; } // determine drawing scale float matrixScale; if (fillPattern.Target == FillPatternTarget.Model) { matrixScale = _scale; } else { matrixScale = _scale * 10; } // prepare pen var pen = new Pen(System.Drawing.Color.Black) { Width = 1f / matrixScale }; try { // setup rectangle and center 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; gfx.ResetTransform(); // draw each fill grid foreach (var fillGrid in fillPattern.GetFillGrids()) { // radian to degree: inline math is faster var degreeAngle = (float)(fillGrid.Angle * 180 / Math.PI); // setup pen dash float dashLength = 1; var segments = fillGrid.GetSegments(); if (segments.Count > 0) { pen.DashPattern = segments.Select(Convert.ToSingle).ToArray(); dashLength = pen.DashPattern.Sum(); } gfx.ResetTransform(); // determine offset and rotation var offset = (-10) * dashLength; var rotateMatrix = new Matrix(); rotateMatrix.Rotate(degreeAngle); var matrix = new Matrix(1, 0, 0, -1, centerX, centerY); matrix.Scale(matrixScale, matrixScale); matrix.Translate((float)fillGrid.Origin.U, (float)fillGrid.Origin.V); // make a copy for backward move var backMatrix = matrix.Clone(); matrix.Multiply(rotateMatrix); matrix.Translate(offset, 0); backMatrix.Multiply(rotateMatrix); backMatrix.Translate(offset, 0); int safety = 250; double alternator = 0; // draw moving forward while (IntersectsWith(matrix, viewRect) && safety > 0) { gfx.Transform = matrix; gfx.DrawLine(pen, 0, 0, _length, 0); matrix.Translate((float)fillGrid.Shift, (float)fillGrid.Offset); alternator += fillGrid.Shift; if (Math.Abs(alternator) > Math.Abs(offset)) { matrix.Translate(offset, 0); alternator = 0d; } --safety; } // draw moving backward safety = 250; alternator = 0; while (IntersectsWith(backMatrix, viewRect) && safety > 0) { gfx.Transform = backMatrix; gfx.DrawLine(pen, 0, 0, _length, 0); backMatrix.Translate(-(float)fillGrid.Shift, -(float)fillGrid.Offset); alternator += fillGrid.Shift; if (Math.Abs(alternator) > Math.Abs(offset)) { backMatrix.Translate(offset, 0); alternator = 0d; } --safety; } } } catch (Exception ex) { logger.Debug(ex.ToString()); } }
private byte[] CreatePdfWithRotatedXObject(String xobjectText) { MemoryStream baos = new MemoryStream(); Document doc = new Document(); PdfWriter writer = PdfWriter.GetInstance(doc, baos); writer.CompressionLevel = 0; doc.Open(); doc.Add(new Paragraph("A")); doc.Add(new Paragraph("B")); bool rotate = true; PdfTemplate template = writer.DirectContent.CreateTemplate(20, 100); template.SetColorStroke(BaseColor.GREEN); template.Rectangle(0, 0, template.Width, template.Height); template.Stroke(); Matrix matrix = new Matrix(); if (rotate) { matrix.Translate(0, template.Height); matrix.Rotate(-90); } template.Transform(matrix); template.BeginText(); template.SetFontAndSize(BaseFont.CreateFont(), 12); if (rotate) template.MoveText(0, template.Width - 12); else template.MoveText(0, template.Height - 12); template.ShowText(xobjectText); template.EndText(); Image xobjectImage = Image.GetInstance(template); if (rotate) xobjectImage.RotationDegrees = 90; doc.Add(xobjectImage); doc.Add(new Paragraph("C")); doc.Close(); return baos.ToArray(); }
// draw Elipse-------------------------------------------------------------------------------------------------------------- private void OnTimerDrwElipse() { Graphics g = bufferedGraphics.Graphics; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; int radius = mSensitivityOfTest / 2; // for circle we need a 360' angle if (angle > 359) { for (int i = 0; i <= 359; i++) { System.Drawing.Drawing2D.Matrix matrix2 = new System.Drawing.Drawing2D.Matrix(); matrix2.Rotate(i, System.Drawing.Drawing2D.MatrixOrder.Append); matrix2.Translate(this.ClientSize.Width / 2, this.ClientSize.Height / 2, System.Drawing.Drawing2D.MatrixOrder.Append); g.Transform = matrix2; g.FillEllipse(Brushes.Yellow, -300, -300, 10, 10); if (!goExit) { bufferedGraphics.Render(Graphics.FromHwnd(this.Handle)); } } angle = 0; foreach (Point p in gazePointListForElips) { g.FillEllipse(Brushes.DeepSkyBlue, p.X - this.ClientSize.Width / 2 - 5, p.Y - this.ClientSize.Height / 2 - 5, 10, 10); if (!goExit) { bufferedGraphics.Render(Graphics.FromHwnd(this.Handle)); } angle++; System.Threading.Thread.Sleep(mDelayFactor); } timer.Stop(); //Save the Image finishTesting = true; saveTheTestingImage("Elipse-Test", gazePointListForElips, shapPointListForElips); g.Clear(Color.Black); doingElipse = false; } // g.Clear(Color.Black); if (angle <= 359 && angle != 0) { int x = (int)(this.Width / 2 + Math.Cos(angle) * 300) - this.ClientSize.Width / 2; int y = (int)(this.Height / 2 + Math.Sin(angle) * 300) - this.ClientSize.Height / 2; System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix(); matrix.Rotate(angle, System.Drawing.Drawing2D.MatrixOrder.Append); matrix.Translate(this.ClientSize.Width / 2, this.ClientSize.Height / 2, System.Drawing.Drawing2D.MatrixOrder.Append); g.Transform = matrix; g.FillEllipse(Brushes.Red, -300, -300, mSensitivityOfTest, mSensitivityOfTest); g.FillEllipse(Brushes.Black, -300 + radius - 3, -300 + radius - 3, 6, 6); //adding to list gazePointListForElips.Add(getGazePoint()); shapPointListForElips.Add(new Point(x, y)); if (!goExit) { bufferedGraphics.Render(Graphics.FromHwnd(this.Handle)); } g.Clear(Color.Black); System.Threading.Thread.Sleep(mDelayFactor); } angle++; //clearScreen //this.Close(); }
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; }
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; }
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(s => Math.Max(float.Epsilon, Convert.ToSingle(s))) .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()); } }