/// <summary> /// Converts the matrix. /// </summary> /// <param name="MediaMatrix">The media matrix.</param> /// <returns></returns> public static dm ConvertMatrix(mm MediaMatrix) { var ret = new dm((float) MediaMatrix.M11, (float) MediaMatrix.M12, (float) MediaMatrix.M21, (float) MediaMatrix.M22, (float) MediaMatrix.OffsetX, (float) MediaMatrix.OffsetY); return ret; }
public void DoPaintRemote(PaintEventArgs e) { var matrix = new System.Drawing.Drawing2D.Matrix(); matrix.Translate(this.Left, this.Top); e.Graphics.Transform = matrix; OnPaint(e); }
/// <summary> /// Draws grid lines corresponding to a vertical scale</summary> /// <param name="g">The Direct2D graphics object</param> /// <param name="transform">Graph (world) to window's client (screen) transform</param> /// <param name="graphRect">Graph rectangle</param> /// <param name="majorSpacing">Scale's major spacing</param> /// <param name="lineBrush">Grid line brush</param> public static void DrawVerticalScaleGrid( this D2dGraphics g, Matrix transform, RectangleF graphRect, int majorSpacing, D2dBrush lineBrush) { double xScale = transform.Elements[0]; RectangleF clientRect = Transform(transform, graphRect); double min = Math.Min(graphRect.Left, graphRect.Right); double max = Math.Max(graphRect.Left, graphRect.Right); double tickAnchor = CalculateTickAnchor(min, max); double step = CalculateStep(min, max, Math.Abs(clientRect.Right - clientRect.Left), majorSpacing, 0.0); if (step > 0) { double offset = tickAnchor - min; offset = offset - MathUtil.Remainder(offset, step) + step; for (double x = tickAnchor - offset; x <= max; x += step) { double cx = (x - graphRect.Left) * xScale + clientRect.Left; g.DrawLine((float)cx, clientRect.Top, (float)cx, clientRect.Bottom, lineBrush); } } }
/// <summary> /// Cloning constructor. /// </summary> protected SpatialTransform(SpatialTransform source, ICloningContext context) { context.CloneFields(source, this); if (source._cumulativeTransform != null) _cumulativeTransform = source._cumulativeTransform.Clone(); if (source._transform != null) _transform = source._transform.Clone(); }
/// <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); } } }
public static SharpMap.Map InitializeMap(int angle, string[] filenames) { var map = new SharpMap.Map(); for (int i = 0; i < filenames.Length; i++) map.Layers.Add(new SharpMap.Layers.GdalRasterLayer(System.IO.Path.GetFileName(filenames[i]), filenames[i])); System.Drawing.Drawing2D.Matrix mat = new System.Drawing.Drawing2D.Matrix(); mat.RotateAt(angle, map.WorldToImage(map.Center)); map.MapTransform = mat; map.ZoomToExtents(); return map; }
/// <summary> /// Initializes a new map /// </summary> /// <param name="size">Size of map in pixels</param> public Map(System.Drawing.Size size) { this.Size = size; this.Layers = new List<SharpMap.Layers.ILayer>(); this.BackColor = System.Drawing.Color.Transparent; this._MaximumZoom = double.MaxValue; this._MinimumZoom = 0; _MapTransform = new System.Drawing.Drawing2D.Matrix(); MapTransformInverted = new System.Drawing.Drawing2D.Matrix(); _Center = new SharpMap.Geometries.Point(0, 0); _Zoom = 1; _PixelAspectRatio = 1.0; }
/// <summary> /// Initializes a new map /// </summary> /// <param name="size">Size of map in pixels</param> public Map(System.Drawing.Size size) { this.Size = size; this.Layers = new SharpMap.Layers.LayerCollection(); this.BackColor = System.Drawing.Color.Transparent; this._MaximumZoom = double.MaxValue; this._MinimumZoom = 0; _MapTransform = new System.Drawing.Drawing2D.Matrix(); MapTransformInverted = new System.Drawing.Drawing2D.Matrix(); _Center = SharpMap.Converters.Geometries.GeometryFactory.CreateCoordinate(0, 0); _Zoom = 1; _PixelAspectRatio = 1.0; }
internal override void Save(FlowChartModel model) { float ZoomFactor = 4.0f; using (Bitmap bmp = new Bitmap((int)(601*ZoomFactor), (int)(851*ZoomFactor))) { using (Graphics g = Graphics.FromImage(bmp)) { System.Drawing.Drawing2D.Matrix mx = new System.Drawing.Drawing2D.Matrix(ZoomFactor, 0, 0, ZoomFactor, 0, 0); g.Transform = mx; g.PageUnit = GraphicsUnit.Pixel; g.Clear(Color.White); g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; model.Items.ForEach(x => { x.View.Draw(g); }); g.Save(); ImageFormat fm = ImageFormat.Bmp; if (Path.GetExtension(fileName).ToLower() == ".png") { fm = System.Drawing.Imaging.ImageFormat.Png; } else if (Path.GetExtension(fileName).ToLower() == ".jpg") { fm = System.Drawing.Imaging.ImageFormat.Jpeg; } else if (Path.GetExtension(fileName).ToLower() == ".jpeg") { fm = System.Drawing.Imaging.ImageFormat.Jpeg; } else if (Path.GetExtension(fileName).ToLower() == ".gif") { fm = System.Drawing.Imaging.ImageFormat.Gif; } else if (Path.GetExtension(fileName).ToLower() == ".tiff") { fm = System.Drawing.Imaging.ImageFormat.Tiff; } bmp.Save(fileName, fm); } } }
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; }
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; }
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; }
public bool DrawNode(Node node, object graphics) { Graphics g = (Graphics)graphics; var m = g.Transform; var saveM = g.Transform.Clone(); // g.SetClip(FillTheGraphicsPath(node.GeometryNode.BoundaryCurve)); // This is supposed to flip the text around its center var c = (float)node.GeometryNode.Center.Y; using (var m2 = new System.Drawing.Drawing2D.Matrix(1, 0, 0, -1, 0, 2 * c)) { m.Multiply(m2); } m.Translate( (float)node.GeometryNode.Center.X, (float)node.GeometryNode.Center.Y); g.Transform = m; var styleStack = GetStyleStack(); var painter = new TextViewPainter( Layout, g, SystemColors.WindowText, SystemColors.Window, SystemFonts.DefaultFont, styleStack); var ptr = new TextPointer { Character = 0, Span = 0, Line = TextModel.StartPosition }; painter.SetSelection(ptr, ptr); painter.PaintGdiPlus(); g.Transform = saveM; g.ResetClip(); saveM.Dispose(); // m.Dispose(); return true;//returning false would enable the default rendering }
bool DrawNode(DrawingNode node, object graphics) { Graphics g = (Graphics)graphics; Image image = ImageOfNode(node); //flip the image around its center using (System.Drawing.Drawing2D.Matrix m = g.Transform) { using (System.Drawing.Drawing2D.Matrix saveM = m.Clone()) { g.SetClip(FillTheGraphicsPath(node.GeometryNode.BoundaryCurve)); using (var m2 = new System.Drawing.Drawing2D.Matrix(1, 0, 0, -1, 0, 2 * (float)node.GeometryNode.Center.Y)) m.Multiply(m2); g.Transform = m; g.DrawImage(image, new PointF((float)(node.GeometryNode.Center.X - node.GeometryNode.Width / 2), (float)(node.GeometryNode.Center.Y - node.GeometryNode.Height / 2))); g.Transform = saveM; } } return true;//returning false would enable the default rendering }
/// <summary> /// Paint the tab /// </summary> /// <param name="e"></param> protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { bool Painting = false; if (Painting) { return; } Painting = true; this.SuspendLayout(); Color RenderBorderColor = new Color(); Color RenderBottomColor = new Color(); Color RenderHighColor = new Color(); Color RenderLowColor = new Color(); System.Drawing.Drawing2D.GraphicsPath GraphicPath = new System.Drawing.Drawing2D.GraphicsPath(); int w = this.Width; CalculateWidth(); if (w != this.Width) { GraphicPath.Dispose(); return; } if (m_Selected) { RenderBorderColor = Helper.RenderColors.BorderColor(m_RenderMode, BorderColor); RenderHighColor = Helper.RenderColors.TabBackHighColor(m_RenderMode, BackHighColor); RenderLowColor = Helper.RenderColors.TabBackLowColor(m_RenderMode, BackLowColor); RenderBottomColor = Helper.RenderColors.TabBackLowColor(m_RenderMode, BackLowColor); } else if (m_Hot) { RenderBorderColor = Helper.RenderColors.BorderColor(m_RenderMode, BorderColor); RenderHighColor = Helper.RenderColors.TabBackHighColor(m_RenderMode, BackHighColor); RenderLowColor = Helper.RenderColors.TabBackLowColor(m_RenderMode, BackLowColor); RenderBottomColor = Helper.RenderColors.BorderColor(m_RenderMode, BorderColor); } else { RenderBorderColor = Helper.RenderColors.BorderColorDisabled(m_RenderMode, BorderColorDisabled); RenderHighColor = Helper.RenderColors.TabBackHighColorDisabled(m_RenderMode, BackHighColorDisabled); RenderLowColor = Helper.RenderColors.TabBackLowColorDisabled(m_RenderMode, BackLowColorDisabled); RenderBottomColor = Helper.RenderColors.BorderColor(m_RenderMode, BorderColor); } e.Graphics.SmoothingMode = m_SmoothingMode; GraphicPath.AddPolygon(GetRegion(Width - 1, Height - 1, System.Convert.ToInt32(this.IsSelected ? Height : Height - 1))); // if is bottom mirror the button vertically if (m_Alignment == TabControl.TabAlignment.Bottom) { MirrorPath(GraphicPath); Color x = RenderHighColor; RenderHighColor = RenderLowColor; RenderLowColor = x; } // Get the correct region including all the borders Region R = new Region(GraphicPath); Region R1 = new Region(GraphicPath); Region R2 = new Region(GraphicPath); Region R3 = new Region(GraphicPath); System.Drawing.Drawing2D.Matrix M1 = new System.Drawing.Drawing2D.Matrix(); System.Drawing.Drawing2D.Matrix M2 = new System.Drawing.Drawing2D.Matrix(); System.Drawing.Drawing2D.Matrix M3 = new System.Drawing.Drawing2D.Matrix(); M1.Translate(0, -0.5F); M2.Translate(0, 0.5F); M3.Translate(1, 0); R1.Transform(M1); R2.Transform(M2); R3.Transform(M3); R.Union(R1); R.Union(R2); R.Union(R3); this.Region = R; RectangleF RF = R.GetBounds(e.Graphics); Rectangle rec = new Rectangle(0, 0, (int)RF.Width, (int)RF.Height); TabControl.TabPaintEventArgs te = default(TabControl.TabPaintEventArgs); te = new TabControl.TabPaintEventArgs(e.Graphics, rec, m_Selected, m_Hot, GraphicPath, Width, Height); if (TabPaintBackgroundEvent != null) // try to owner draw { TabPaintBackgroundEvent(this, te); } System.Drawing.Drawing2D.LinearGradientBrush gb = CreateGradientBrush(new Rectangle(0, 0, this.Width, this.Height), RenderHighColor, RenderLowColor); if (!te.Handled) { e.Graphics.FillPath(gb, GraphicPath); } gb.Dispose(); te.Dispose(); te = new TabControl.TabPaintEventArgs(e.Graphics, rec, m_Selected, m_Hot, GraphicPath, Width, Height); if (TabPaintBorderEvent != null) // try to owner draw { TabPaintBorderEvent(this, te); } if (!te.Handled) { if (m_BorderEnhanced) { Color c = m_Alignment == TabControl.TabAlignment.Bottom ? RenderLowColor : RenderHighColor; Pen p = new Pen(c, (float)m_BorderEnhanceWeight); e.Graphics.DrawLines(p, GraphicPath.PathPoints); p.Dispose(); } Pen p1 = new Pen(RenderBorderColor); e.Graphics.DrawLines(p1, GraphicPath.PathPoints); p1.Dispose(); } te.Dispose(); e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None; e.Graphics.DrawLine(new Pen(RenderBottomColor), GraphicPath.PathPoints[0], GraphicPath.PathPoints[GraphicPath.PointCount - 1]); e.Graphics.SmoothingMode = m_SmoothingMode; DrawIcon(e.Graphics); DrawText(e.Graphics); if (m_CloseButtonVisible) { DrawCloseButton(e.Graphics); } this.ResumeLayout(); // do the memory cleanup GraphicPath.Dispose(); M1.Dispose(); M2.Dispose(); M3.Dispose(); R1.Dispose(); R2.Dispose(); R3.Dispose(); R.Dispose(); te.Dispose(); Painting = false; }
internal virtual int getDrawType(DrawContext context, System.Drawing.Drawing2D.Matrix transform, ScenicColor color) { return(DRAW_SIMPLE); }
internal override void prepareDraw(DrawContext context, System.Drawing.Drawing2D.Matrix transform) { }
internal void DrawHorizontal(Chart chart, Rdl.Runtime.Context context, Graphics g, bool centered, int l, int t, int w, ref int h) { int majorIntervals = (int)((_maxValue - _minValue) / _majorIntervalValue); int minorIntervals = (int)((_maxValue - _minValue) / _minorIntervalValue); // Find the tick mark and axis position for the axis. int majorTickStart, majorTickHeight, minorTickStart, minorTickHeight, axisPos, axisWidth; AdjustAxisPosition(GetAxisThickness(context), out majorTickStart, out majorTickHeight, out minorTickStart, out minorTickHeight, out axisPos, out axisWidth); Color color = Style.W32Color(Style.Color(context)); Brush brush = new SolidBrush(color); Pen majorGridPen = new Pen(brush, 1); if (MajorGridLines != null) { majorGridPen = new Pen(new SolidBrush(Style.W32Color(MajorGridLines.Style.Color(context))), (int)MajorGridLines.Style.BorderWidth.Left(context).points); } Pen minorGridPen = new Pen(brush, 1); if (MinorGridLines != null) { minorGridPen = new Pen(new SolidBrush(Style.W32Color(MinorGridLines.Style.Color(context))), (int)MinorGridLines.Style.BorderWidth.Left(context).points); } Font font = Style.GetWindowsFont(context); bool vertical = false; float yMult = (float)g.DpiY / 72; int labelHeight = 0; float majorEntryWidth = (float)w / majorIntervals; float minorEntryWidth = (float)w / minorIntervals; // Determine how much vertical space is required for the axis labels. if (Visible) { // Determine if the labels need to be vertical and find the height required for the labels. labelHeight = (int)(font.Height * yMult); // Determine the amount of space required for the axis labels. GetValueLableWidth(context, g, majorIntervals); if (_labelWidth > (int)majorEntryWidth) { labelHeight = _labelWidth; vertical = true; } } // If we are showing the grid lines then adjust the tick width to include the whole chart area. if (MajorGridLines.ShowGridLines) { majorTickHeight = h - labelHeight - axisPos - majorTickStart; } if (MinorGridLines.ShowGridLines) { minorTickHeight = h - labelHeight - axisPos - minorTickStart; } // Fill in the background of the plot area. g.FillRectangle(new SolidBrush(Style.W32Color(chart.PlotAreaStyle.BackgroundColor(context))), l, t, w, h - (labelHeight + axisWidth)); // Draw the axis line g.DrawLine(new Pen(new SolidBrush(color), GetAxisThickness(context)), new Point(l, t + h - labelHeight - axisPos - (GetAxisThickness(context) >> 1)), new Point(l + w, t + h - labelHeight - axisPos - (GetAxisThickness(context) >> 1))); // Loop through the major interval values int left = l; for (int i = 0; i <= majorIntervals; i++) { left = l + (int)(i * majorEntryWidth); if (Visible) { decimal dValue = _minValue + (i * _majorIntervalValue); int center = left; if (centered) { center += (int)(majorEntryWidth / 2); } SizeF size = g.MeasureString(dValue.ToString(), font); if (vertical) { System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath(); path.AddString(dValue.ToString(), font.FontFamily, (int)font.Style, font.Size * yMult, new Point(center - ((int)size.Width / 2), t + h - labelHeight), StringFormat.GenericDefault); if (vertical) { System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix(); matrix.Translate(0 - (size.Width / 2), 0); matrix.RotateAt(-30, new PointF(center, t + h - labelHeight), System.Drawing.Drawing2D.MatrixOrder.Append); path.Transform(matrix); } g.DrawPath(new Pen(brush), path); } else { g.DrawString(dValue.ToString(), font, brush, center - (int)size.Width / 2, t + h - labelHeight, StringFormat.GenericDefault); } } if (i > 0) { // Draw the major tick mark if (majorTickHeight > 0) { g.DrawLine(majorGridPen, new Point(left, t + h - labelHeight - (axisWidth >> 1) - majorTickStart), new Point(left, t + h - labelHeight - (axisWidth >> 1) - majorTickStart - majorTickHeight)); } // Draw the minor tick marks if (minorTickHeight > 0) { for (int j = 1; j < minorIntervals / majorIntervals; j++) { g.DrawLine(minorGridPen, new Point(left + (int)(j * minorEntryWidth), t + h - labelHeight - (axisWidth >> 1) + minorTickStart), new Point(left + (int)(j * minorEntryWidth), t + h - labelHeight - (axisWidth >> 1) + minorTickStart - minorTickHeight)); } } } } h -= labelHeight + ((axisWidth + GetAxisThickness(context)) >> 1); }
public override void Draw(int gridSize, Graphics g) { int deltaX = (End.X - Start.X); int deltaY = (End.Y - Start.Y); // This is the size of the rectangle that will hold the ellipse SizeF arcSizeRotate = new SizeF((float)Length * gridSize, (float)(Radius * 2 * gridSize)); // Perform the rotations and translations. using (System.Drawing.Drawing2D.Matrix transformMatrix = new System.Drawing.Drawing2D.Matrix()) { Point start = Start.ToPoint(gridSize); Point end = End.ToPoint(gridSize); // We might need to swap what we consider as start/end. if (Start.X > End.X || Start.Y < End.Y) { start = End.ToPoint(gridSize); end = Start.ToPoint(gridSize); } // Calculate angle from offset. double radians = Math.Atan((double)(end.Y - start.Y) / (double)(end.X - start.X)); double degrees = radians * ((double)180 / Math.PI); // Rotate by the specified angle transformMatrix.RotateAt((float)degrees, start, System.Drawing.Drawing2D.MatrixOrder.Prepend); // Convert back into radians, but with the absolute value for degrees. degrees = Math.Abs(degrees) * Math.PI / 180; int signX = Math.Sign(deltaX); int signY = Math.Sign(deltaY); // translate by the width of the line as the box is drawn away from the line if (signX == 1 && signY == 1) { transformMatrix.Translate(-(float)(Math.Cos(degrees) * (arcSizeRotate.Width)), 0, System.Drawing.Drawing2D.MatrixOrder.Append); transformMatrix.Translate(0, -(float)(Math.Sin(degrees) * (arcSizeRotate.Width)), System.Drawing.Drawing2D.MatrixOrder.Append); } // always translate on the x axis transformMatrix.Translate(0, -(float)(Math.Cos(degrees) * (arcSizeRotate.Height / 2)), System.Drawing.Drawing2D.MatrixOrder.Append); // translate on the y axis eiter by adding or substracting depending on the way the line was drawn transformMatrix.Translate((signY == signX ? 1 : -1) * (float)(Math.Sin(degrees) * (arcSizeRotate.Height / 2)), 0, System.Drawing.Drawing2D.MatrixOrder.Append); //figure out the angle int startDegrees = 180; if (signX == -1 || (signX == 0 && signY == 1)) { startDegrees = 0; } g.Transform = transformMatrix; Pen pen = new Pen(new SolidBrush(Color), Width); g.DrawArc(pen, new RectangleF(start, arcSizeRotate), (float)(startDegrees), (float)(180)); g.ResetTransform(); } }
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); }
private static void DrawGraph(Bitmap bitmap, GleeGraph graph) { var graphics = Graphics.FromImage(bitmap); graphics.Clear(Color.White); var matrix = new System.Drawing.Drawing2D.Matrix(); matrix.Translate(-(float)graph.BoundingBox.Left, -(float)graph.BoundingBox.Bottom); graphics.Transform = matrix; // Nodes foreach (var node in graph.NodeMap.Values) { ICurve curve = node.MovedBoundaryCurve; Ellipse el = curve as Ellipse; if (el != null) { graphics.DrawEllipse(nodePen, new RectangleF((float)el.BBox.Left, (float)el.BBox.Bottom, (float)el.BBox.Width, (float)el.BBox.Height)); var font = (node.Id == startNode) ? startNodeFont : nodeFont; var textBrush = (node.Id == startNode) ? startNodeTextBrush : nodeTextBrush; graphics.DrawString( node.Id, font, textBrush, new RectangleF((float)el.BBox.Left, (float)el.BBox.Bottom, (float)el.BBox.Width, (float)el.BBox.Height), stringFormat); } } // Edges foreach (var edge in graph.Edges) { ICurve curve = edge.Curve; var c = curve as Curve; if (c != null) { foreach (ICurve s in c.Segs) { var l = s as LineSeg; if (l != null) { graphics.DrawLine(edgePen, GleePointToDrawingPoint(l.Start), GleePointToDrawingPoint(l.End)); } var cs = s as CubicBezierSeg; if (cs != null) { graphics.DrawBezier(edgePen, GleePointToDrawingPoint(cs.B(0)), GleePointToDrawingPoint(cs.B(1)), GleePointToDrawingPoint(cs.B(2)), GleePointToDrawingPoint(cs.B(3))); } } if (edge.ArrowHeadAtSource) { DrawArrow(edge, edgePen, graphics, edge.Curve.Start, edge.ArrowHeadAtSourcePosition); } if (edge.ArrowHeadAtTarget) { DrawArrow(edge, edgePen, graphics, edge.Curve.End, edge.ArrowHeadAtTargetPosition); } if (c.Segs.Count % 2 == 0) { // Even segs var index = c.Segs.Count / 2; var l = c.Segs[index] as LineSeg; if (l != null) { var p = GleePointToDrawingPoint(l.End); DrawEdgeLabel(graphics, edge, p.X, p.Y); } var cs = c.Segs[index] as CubicBezierSeg; if (cs != null) { var p = GleePointToDrawingPoint(cs.B(2)); DrawEdgeLabel(graphics, edge, p.X, p.Y); } } else { // Uneven segs var index = c.Segs.Count / 2; var l = c.Segs[index] as LineSeg; if (l != null) { var p1 = GleePointToDrawingPoint(l.Start); var p2 = GleePointToDrawingPoint(l.End); DrawEdgeLabel(graphics, edge, (p2.X - p1.X) / 2, (p2.Y - p1.Y) / 2); } var cs = c.Segs[index] as CubicBezierSeg; if (cs != null) { var p = GleePointToDrawingPoint(cs.B(1)); DrawEdgeLabel(graphics, edge, p.X, p.Y); } } } } graphics.Flush(); }
public void MultiplyTransform(System.Drawing.Drawing2D.Matrix matrix, System.Drawing.Drawing2D.MatrixOrder order) { }
public void MultiplyTransform(System.Drawing.Drawing2D.Matrix matrix) { }
public Bitmap GetScaledImage(System.Drawing.Drawing2D.Matrix m) { return(stage.Gdi.RenderFirstFrame(definition, m)); }
/// <summary> /// Update function of map. Calls Bayes filtering and handles the rotation and translation of all map objects. /// </summary> private void Update(object sender, EventArgs e) { lock (robot.mapLock) { Bayes(true, preySensor, ref preyProbability); Bayes(false, obstacleSensor, ref obstacleProbability); bBayes = new Bitmap(bMap.Size.Width, bMap.Size.Height); SetNewRovioPosition(); // Run AStar if there is a suitable destination and draw it on the map. using (graphics = Graphics.FromImage(bBayes)) { AStar astar = new AStar(finalMap.GetLength(0), finalMap.GetLength(1)); astar.Build(finalMap, new DPoint(destination.X, destination.Y), new DPoint((picBoxRovio.Location.X / 10) + (picBoxRovio.Width / 10 / 2), picBoxRovio.Location.Y / 10)); aStarPath = astar.path; for (int i = 0; i < maxX; i++) { for (int j = 0; j < maxY; j++) { graphics.FillRectangle(new SolidBrush(DColor.FromArgb((int)(preyProbability[i, j] * 255), System.Drawing.Color.DarkRed)), new DRectangle(i * 10, j * 10, 10, 10)); graphics.FillRectangle(new SolidBrush(DColor.FromArgb((int)(obstacleProbability[i, j] * 255), System.Drawing.Color.DarkBlue)), new DRectangle(i * 10, j * 10, 10, 10)); if (astar.inPath[i, j]) { graphics.FillRectangle(new SolidBrush(DColor.Red), new DRectangle(i * 10, j * 10, 10, 10)); } } } } picBoxBayes.Image = bBayes; // Check which cells are within the viewing cone. if (viewConePoints != null) { for (int i = 0; i < maxX; i++) { for (int j = 0; j < maxY; j++) { DPoint a = new DPoint(i * 10 + 1, j * 10 + 1); // Top left DPoint b = new DPoint((i + 1) * 10 - 1, j * 10 + 1); // Top right DPoint c = new DPoint(i * 10 + 1, (j + 1) * 10 - 1); // Bottom left DPoint d = new DPoint((i + 1) * 10 - 1, (j + 1) * 10 - 1); // Bottom right if (!(PointInPolygon(a, viewConePoints) || PointInPolygon(b, viewConePoints) || PointInPolygon(c, viewConePoints) || PointInPolygon(d, viewConePoints))) { isCellVisible[i, j] = false; } else { preySensor[i, j] = false; obstacleSensor[i, j] = false; isCellVisible[i, j] = true; } } } } if (robot.GetType() == typeof(Rovio.PredatorMap)) { if (robot.IsPreySeen()) { FindRelativeLocation(picBoxPrey, robot.preyRectangle, robot.GetPreyDistance(), 1, 1); try { preySensor[(int)((picBoxPrey.Location.X / 10) + 1.5), (int)((picBoxPrey.Location.Y / 10) + 1.5)] = true; } catch { } } else { picBoxPrey.Hide(); } if ((robot as Rovio.BaseArena).IsObstacleSeen()) { // Find obstacle position relative to the Rovio's position. FindRelativeLocation(picBoxObstacle, robot.obstacleRectangle, robot.GetObstacleDistance(), 40, 3); try { int p = (int)((picBoxObstacle.Location.X / 10) + 0.5); int q = (int)((picBoxObstacle.Location.Y / 10) + 0.5); // Populate 3x3 area with the obstacle. for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { obstacleSensor[(int)((picBoxObstacle.Location.X / 10) + i), (int)((picBoxObstacle.Location.Y / 10) + j)] = true; } } } catch { } } else { picBoxObstacle.Hide(); } } // Rotate the Rovio icon to the angle that the robot physically faces. System.Drawing.Drawing2D.Matrix matrixRovio = new System.Drawing.Drawing2D.Matrix(); matrixRovio.RotateAt((float)robot.cumulativeAngle, new System.Drawing.Point(picBoxRovio.Location.X + (picBoxRovio.Size.Width / 2), picBoxRovio.Location.Y + (picBoxRovio.Size.Height / 2))); matrixRovio.Translate(0f, -0f); DPoint[] rovioMovementPoints = { new DPoint(picBoxRovio.Location.X + (picBoxRovio.Size.Width / 2), picBoxRovio.Location.Y + (picBoxRovio.Size.Height / 2)), new DPoint(picBoxRovio.Location.X + (picBoxRovio.Size.Width / 2) - 69, picBoxRovio.Location.Y - 150), new DPoint(picBoxRovio.Location.X + (picBoxRovio.Size.Width / 2) + 69, picBoxRovio.Location.Y - 150) }; matrixRovio.TransformPoints(rovioMovementPoints); if ((robot as Rovio.BaseArena).IsObstacleSeen()) { // Get the left and right points of the obstacle in the viewing cone and orientate accordingly. DPoint leftPoint = new DPoint(picBoxObstacle.Location.X - (picBoxObstacle.Width / 2), picBoxObstacle.Location.Y - 15); DPoint rightPoint = leftPoint; using (matrix = new System.Drawing.Drawing2D.Matrix()) { matrix.RotateAt((float)robot.cumulativeAngle, leftPoint); matrix.Translate(0, -0f); DPoint[] tempPointArr = { leftPoint }; matrix.TransformPoints(tempPointArr); leftPoint = tempPointArr[0]; // Transform the right point relative to the position of the left. matrix = new System.Drawing.Drawing2D.Matrix(); matrix.RotateAt((float)robot.cumulativeAngle, leftPoint); matrix.Translate(30, 0); tempPointArr[0] = new DPoint(0, 0); matrix.TransformPoints(tempPointArr); rightPoint = tempPointArr[0]; } // Check if all points are still within the viewing cone. If not, skip over them. if (PointInPolygon(leftPoint, rovioMovementPoints) && PointInPolygon(rightPoint, rovioMovementPoints)) { rovioMovementPoints = new DPoint[] { rovioMovementPoints[0], rovioMovementPoints[1], leftPoint, rightPoint, rovioMovementPoints[2] } } ; } viewConePoints = rovioMovementPoints; Bitmap rotated = new Bitmap(bRovio.Width + 70, bRovio.Height + 70); rotated.SetResolution(bRovio.HorizontalResolution, bRovio.VerticalResolution); using (graphics = Graphics.FromImage(rotated)) { graphics.TranslateTransform(bRovio.Width / 2, bRovio.Height / 2); graphics.RotateTransform((float)robot.cumulativeAngle); graphics.TranslateTransform(-bRovio.Width / 2, -bRovio.Height / 2); graphics.DrawImage(bRovio, new DPoint(0, 0)); picBoxRovio.Size = new Size(27, 24); picBoxRovio.Image = rotated; picBoxCone.Location = new DPoint(picBoxRovio.Location.X - (bCone.Width / 2) + (bRovio.Width / 2), picBoxRovio.Location.Y - bCone.Height + (bRovio.Height / 2)); picBoxCone.Size = new Size(900, 500); picBoxCone.Image = rotated; picBoxCone.Location = new DPoint(0, 0); picBoxCone.Size = new Size(260, 300); } Bitmap newCone = new Bitmap(260, 300); using (graphics = Graphics.FromImage(newCone)) { graphics.FillPolygon(new SolidBrush(DColor.FromArgb(100, DColor.ForestGreen)), viewConePoints); picBoxCone.Image = newCone; } } }
public static v2 TransformPoint(this Matrix m, v2 pt) { return(v2.From(m.TransformPoint(pt.ToPointF()))); }
public List<Point> ToPoints( float angle, Rectangle rect) { // Create a GraphicsPath. System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath(); path.AddRectangle(rect); // Declare a matrix that will be used to rotate the text. System.Drawing.Drawing2D.Matrix rotateMatrix = new System.Drawing.Drawing2D.Matrix(); // Set the rotation angle and starting point for the text. rotateMatrix.RotateAt(180.0F, new PointF(10.0F, 100.0F)); // Transform the text with the matrix. path.Transform(rotateMatrix); List<Point> results = new List<Point>(); foreach(PointF p in path.PathPoints) { results.Add(new Point((int)p.X, (int)p.Y)); } path.Dispose(); return results; }
/// <summary> /// Applies same transform to GDI</summary> private void ApplyXformToGdi() { using (var xform = new System.Drawing.Drawing2D.Matrix(m_xform.M11, m_xform.M12, m_xform.M21, m_xform.M22 , m_xform.DX, m_xform.DY)) { m_graphics.Transform = xform; } }
/// <summary> /// Gives subclasses an opportunity to perform a post-transform transformation. /// </summary> protected virtual void CalculatePostTransform(Matrix cumulativeTransform) { cumulativeTransform.Translate(-_centerOfRotationXY.X, -_centerOfRotationXY.Y); }
public static void Run() { // ExStart:ImageInformation // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Images(); // Load the source PDF file Document doc = new Document(dataDir + "ImageInformation.pdf"); // Define the default resolution for image int defaultResolution = 72; System.Collections.Stack graphicsState = new System.Collections.Stack(); // Define array list object which will hold image names System.Collections.ArrayList imageNames = new System.Collections.ArrayList(doc.Pages[1].Resources.Images.Names); // Insert an object to stack graphicsState.Push(new System.Drawing.Drawing2D.Matrix(1, 0, 0, 1, 0, 0)); // Get all the operators on first page of document foreach (Operator op in doc.Pages[1].Contents) { // Use GSave/GRestore operators to revert the transformations back to previously set Operator.GSave opSaveState = op as Operator.GSave; Operator.GRestore opRestoreState = op as Operator.GRestore; // Instantiate ConcatenateMatrix object as it defines current transformation matrix. Operator.ConcatenateMatrix opCtm = op as Operator.ConcatenateMatrix; // Create Do operator which draws objects from resources. It draws Form objects and Image objects Operator.Do opDo = op as Operator.Do; if (opSaveState != null) { // Save previous state and push current state to the top of the stack graphicsState.Push(((System.Drawing.Drawing2D.Matrix)graphicsState.Peek()).Clone()); } else if (opRestoreState != null) { // Throw away current state and restore previous one graphicsState.Pop(); } else if (opCtm != null) { System.Drawing.Drawing2D.Matrix cm = new System.Drawing.Drawing2D.Matrix( (float)opCtm.Matrix.A, (float)opCtm.Matrix.B, (float)opCtm.Matrix.C, (float)opCtm.Matrix.D, (float)opCtm.Matrix.E, (float)opCtm.Matrix.F); // Multiply current matrix with the state matrix ((System.Drawing.Drawing2D.Matrix)graphicsState.Peek()).Multiply(cm); continue; } else if (opDo != null) { // In case this is an image drawing operator if (imageNames.Contains(opDo.Name)) { System.Drawing.Drawing2D.Matrix lastCTM = (System.Drawing.Drawing2D.Matrix)graphicsState.Peek(); // Create XImage object to hold images of first pdf page XImage image = doc.Pages[1].Resources.Images[opDo.Name]; // Get image dimensions double scaledWidth = Math.Sqrt(Math.Pow(lastCTM.Elements[0], 2) + Math.Pow(lastCTM.Elements[1], 2)); double scaledHeight = Math.Sqrt(Math.Pow(lastCTM.Elements[2], 2) + Math.Pow(lastCTM.Elements[3], 2)); // Get Height and Width information of image double originalWidth = image.Width; double originalHeight = image.Height; // Compute resolution based on above information double resHorizontal = originalWidth * defaultResolution / scaledWidth; double resVertical = originalHeight * defaultResolution / scaledHeight; // Display Dimension and Resolution information of each image Console.Out.WriteLine( string.Format(dataDir + "image {0} ({1:.##}:{2:.##}): res {3:.##} x {4:.##}", opDo.Name, scaledWidth, scaledHeight, resHorizontal, resVertical)); } } } // ExEnd:ImageInformation }
public void MouseMoveUpdate(object sender, System.Windows.Input.MouseEventArgs e) { double gapX, gapY, x, y; if (shapeLib.Data.gdc.bmove) { gapX = Math.Abs(shapeLib.Data.currShape.controlBtn4.X + shapeLib.Data.currShape.controlBtn1.X) / 2.0; gapY = Math.Abs(shapeLib.Data.currShape.controlBtn4.Y + shapeLib.Data.currShape.controlBtn1.Y) / 2.0; x = e.GetPosition(shapeLib.Data.mygrid).X; y = e.GetPosition(shapeLib.Data.mygrid).Y; shapeLib.Data.currShape.controlBtn4.X = shapeLib.Data.currShape.controlBtn4.X + (x - gapX); shapeLib.Data.currShape.controlBtn4.Y = shapeLib.Data.currShape.controlBtn4.Y + (y - gapY); shapeLib.Data.currShape.controlBtn1.X = shapeLib.Data.currShape.controlBtn1.X + (x - gapX); shapeLib.Data.currShape.controlBtn1.Y = shapeLib.Data.currShape.controlBtn1.Y + (y - gapY); shapeLib.Data.currShape.controlBtn2.X = shapeLib.Data.currShape.controlBtn2.X + (x - gapX); shapeLib.Data.currShape.controlBtn2.Y = shapeLib.Data.currShape.controlBtn2.Y + (y - gapY); shapeLib.Data.currShape.controlBtn3.X = shapeLib.Data.currShape.controlBtn3.X + (x - gapX); shapeLib.Data.currShape.controlBtn3.Y = shapeLib.Data.currShape.controlBtn3.Y + (y - gapY); shapeLib.Data.currShape.redraw(1); } if (shapeLib.Data.gdc.bbegrotate) { gapX = Math.Abs(shapeLib.Data.currShape.controlBtn4.X + shapeLib.Data.currShape.controlBtn1.X) / 2.0; gapY = Math.Abs(shapeLib.Data.currShape.controlBtn4.Y + shapeLib.Data.currShape.controlBtn1.Y) / 2.0; x = e.GetPosition(shapeLib.Data.mygrid).X; y = e.GetPosition(shapeLib.Data.mygrid).Y; double dx = x - gapX; double dy = y - gapY; double angle = Math.Atan2(dy, dx); double CurrentAngle = angle * 180 / Math.PI; CurrentAngle = CurrentAngle - shapeLib.Data.gdc.totalAngle; System.Drawing.Drawing2D.Matrix rotate_at_center = new System.Drawing.Drawing2D.Matrix(); rotate_at_center.RotateAt((float )CurrentAngle, new System.Drawing.PointF((float)gapX, (float)gapY)); PointF[] myArray = { new PointF((float)shapeLib.Data.currShape.controlBtn1.X, (float)shapeLib.Data.currShape.controlBtn1.Y), new PointF((float)shapeLib.Data.currShape.controlBtn2.X, (float)shapeLib.Data.currShape.controlBtn2.Y), new PointF((float)shapeLib.Data.currShape.controlBtn3.X, (float)shapeLib.Data.currShape.controlBtn3.Y), new PointF((float)shapeLib.Data.currShape.controlBtn4.X, (float)shapeLib.Data.currShape.controlBtn4.Y) }; rotate_at_center.TransformPoints(myArray); shapeLib.Data.currShape.controlBtn1.X = myArray[0].X; shapeLib.Data.currShape.controlBtn1.Y = myArray[0].Y; shapeLib.Data.currShape.controlBtn2.X = myArray[1].X; shapeLib.Data.currShape.controlBtn2.Y = myArray[1].Y; shapeLib.Data.currShape.controlBtn3.X = myArray[2].X; shapeLib.Data.currShape.controlBtn3.Y = myArray[2].Y; shapeLib.Data.currShape.controlBtn4.X = myArray[3].X; shapeLib.Data.currShape.controlBtn4.Y = myArray[3].Y; shapeLib.Data.gdc.totalAngle += CurrentAngle; shapeLib.Data.currShape.redraw(1); } // throw new NotImplementedException(); }
public CachedFont(System.Drawing.Font font, System.Drawing.Drawing2D.Matrix transform) { this.font = font; this.transform = transform; }
public virtual void walk(PathWalker walker, System.Drawing.Drawing2D.Matrix errorMatrix, double error) { //UPGRADE_TODO: Interface 'java.awt.geom.PathIterator' was converted to 'System.Drawing.Drawing2D.GraphicsPathIterator' which has a different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1073_3"' //UPGRADE_TODO: Method 'java.awt.Shape.getPathIterator' was converted to 'System.Drawing.Drawing2D.GraphicsPathIterator.GraphicsPathIterator' which has a different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1073_javaawtShapegetPathIterator_javaawtgeomAffineTransform_double_3"' System.Drawing.Drawing2D.GraphicsPathIterator itr = new System.Drawing.Drawing2D.GraphicsPathIterator(shape); double[] point = new double[6]; int i = 0; System.Drawing.Drawing2D.Matrix inv; double m00, m01, m10, m11, dx, dy; try { System.Drawing.Drawing2D.Matrix temp_Matrix; temp_Matrix = new System.Drawing.Drawing2D.Matrix(); temp_Matrix = errorMatrix.Clone(); temp_Matrix.Invert(); inv = temp_Matrix; } catch (System.Exception e) { return; } m00 = (float)inv.Elements.GetValue(0); m01 = (float)inv.Elements.GetValue(2); m10 = (float)inv.Elements.GetValue(1); m11 = (float)inv.Elements.GetValue(3); dx = (System.Single)inv.OffsetX; dy = (System.Single)inv.OffsetY; //UPGRADE_ISSUE: Method 'java.awt.geom.PathIterator.isDone' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaawtgeomPathIteratorisDone_3"' while (!itr.isDone()) { //UPGRADE_ISSUE: Method 'java.awt.geom.PathIterator.currentSegment' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaawtgeomPathIteratorcurrentSegment_double[]_3"' int type = itr.currentSegment(point); //UPGRADE_ISSUE: Method 'java.awt.geom.PathIterator.next' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaawtgeomPathIteratornext_3"' itr.next(); //UPGRADE_ISSUE: Field 'java.awt.geom.PathIterator.SEG_MOVETO' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaawtgeomPathIteratorSEG_MOVETO_f_3"' if (type == PathIterator.SEG_MOVETO) { if (i > 0) { walk(walker, points, i, false); i = 0; } points[i++] = m00 * point[0] + m01 * point[1] + dx; points[i++] = m10 * point[0] + m11 * point[1] + dy; } else { //UPGRADE_ISSUE: Field 'java.awt.geom.PathIterator.SEG_LINETO' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaawtgeomPathIteratorSEG_LINETO_f_3"' if (type == PathIterator.SEG_LINETO) { points[i++] = m00 * point[0] + m01 * point[1] + dx; points[i++] = m10 * point[0] + m11 * point[1] + dy; } else { //UPGRADE_ISSUE: Field 'java.awt.geom.PathIterator.SEG_CLOSE' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaawtgeomPathIteratorSEG_CLOSE_f_3"' if (type == PathIterator.SEG_CLOSE) { if (i > 0) { walk(walker, points, i, true); i = 0; } } } } } if (i > 0) { walk(walker, points, i, false); i = 0; } }
internal abstract void draw(DrawContext context, System.Drawing.Drawing2D.Matrix transform, ScenicColor color);
/// <summary> 一个点绕中心点旋转一定角度到达的新坐标 /// </summary> /// <param name="p">点</param> /// <param name="center">中心点</param> /// <param name="angle">角度</param> /// <returns>旋转后的点</returns> public static PointF PointRotate(PointF p, PointF center, float angle) { System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix(); m.RotateAt(angle, new PointF(center.X - p.X, center.Y - p.Y)); return(new PointF(p.X + m.OffsetX, p.Y + m.OffsetY)); }
internal override int getDrawType(DrawContext context, System.Drawing.Drawing2D.Matrix transform) { return(getDrawType(context, transform, color)); }
/// <summary> /// Coberts a <see cref="System.Drawing.Drawing2D.Matrix"/> to <see cref="Fusee.Math.Core.Matrix2F"/>. /// </summary> /// <param name="value">A <see cref="System.Drawing.Drawing2D.Matrix"/> instance to convert.</param> /// <returns>A <see cref="Fusee.Math.Core.Matrix2F"/> instance.</returns> public static Fusee.Math.Core.Matrix2F ToGDI(System.Drawing.Drawing2D.Matrix value) { return(new Fusee.Math.Core.Matrix2F( value.Elements[0], value.Elements[1], value.Elements[2], value.Elements[3])); }
public virtual System.Drawing.Rectangle getBounds(System.Drawing.Drawing2D.Matrix transform) { System.Drawing.Rectangle tempAux = System.Drawing.Rectangle.Truncate(shape.GetBounds()); //UPGRADE_NOTE: ref keyword was added to struct-type parameters. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1303_3"' return(Util.transform(transform, ref tempAux)); }
// Generates the close button image private Bitmap GetButton() { System.Drawing.Point[] Points = new System.Drawing.Point[] { new Point(1, 0), new Point(3, 0), new Point(5, 2), new Point(7, 0), new Point(9, 0), new Point(6, 3), new Point(6, 4), new Point(9, 7), new Point(7, 7), new Point(5, 5), new Point(3, 7), new Point(1, 7), new Point(4, 4), new Point(4, 3) }; System.Drawing.Drawing2D.GraphicsPath gp = new System.Drawing.Drawing2D.GraphicsPath(); Color bch = new Color(); Color bcl = new Color(); Color bc = new Color(); Color fc = new Color(); Bitmap B = default(Bitmap); System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix(); System.Drawing.Point[] path = new System.Drawing.Point[] { new Point(0, 1), new Point(1, 0), new Point(15, 0), new Point(16, 1), new Point(16, 14), new Point(15, 15), new Point(1, 15), new Point(0, 14) }; Graphics g = default(Graphics); if (MouseOverCloseButton) { bch = Helper.RenderColors.TabCloseButtonBackHighColorHot(m_RenderMode, CloseButtonBackHighColorHot); bcl = Helper.RenderColors.TabCloseButtonBackLowColorHot(m_RenderMode, CloseButtonBackLowColorHot); bc = Helper.RenderColors.TabCloseButtonBorderColorHot(m_RenderMode, CloseButtonBorderColorHot); fc = Helper.RenderColors.TabCloseButtonForeColorHot(m_RenderMode, CloseButtonForeColorHot); } else if (m_Selected) { bch = Helper.RenderColors.TabCloseButtonBackHighColor(m_RenderMode, CloseButtonBackHighColor); bcl = Helper.RenderColors.TabCloseButtonBackLowColor(m_RenderMode, CloseButtonBackLowColor); bc = Helper.RenderColors.TabCloseButtonBorderColor(m_RenderMode, CloseButtonBorderColor); fc = Helper.RenderColors.TabCloseButtonForeColor(m_RenderMode, CloseButtonForeColor); } else { bch = Helper.RenderColors.TabCloseButtonBackHighColorDisabled(m_RenderMode, CloseButtonBackHighColorDisabled); bcl = Helper.RenderColors.TabCloseButtonBackLowColorDisabled(m_RenderMode, CloseButtonBackLowColorDisabled); bc = Helper.RenderColors.TabCloseButtonBorderColorDisabled(m_RenderMode, CloseButtonBorderColorDisabled); fc = Helper.RenderColors.TabCloseButtonForeColorDisabled(m_RenderMode, CloseButtonForeColorDisabled); } B = new Bitmap(17, 17); B.MakeTransparent(); g = Graphics.FromImage(B); // draw the border and background g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; System.Drawing.Drawing2D.LinearGradientBrush l = new System.Drawing.Drawing2D.LinearGradientBrush(new Point(0, 0), new Point(0, 15), bch, bcl); g.FillPolygon(l, path); Pen p = new Pen(bc); g.DrawPolygon(p, path); g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.Default; // draw the foreground gp.AddPolygon(Points); m.Translate(3, 4); gp.Transform(m); p.Dispose(); p = new Pen(fc); g.DrawPolygon(p, gp.PathPoints); SolidBrush sb = new SolidBrush(fc); g.FillPolygon(sb, gp.PathPoints); sb.Dispose(); p.Dispose(); gp.Dispose(); g.Dispose(); m.Dispose(); return(B); }
//private Matrix matrix; //private readonly Matrix _inverse; /// <summary> /// Creates an instance of this class /// </summary> /// <param name="matrix"><see cref="T:System.Drawing.Drawing2D.Matrix"/> that holds the coefficients and for the coordinate transformation</param> public AffineCoordinateTransformation2D(System.Drawing.Drawing2D.Matrix matrix) : this( matrix.Elements[0], matrix.Elements[1], matrix.OffsetX, matrix.Elements[2], matrix.Elements[3], matrix.OffsetY) { }
internal static SharpMap.Map InitializeMap(float angle, string[] filenames) { var map = new SharpMap.Map(); try { foreach (var filename in filenames) { var connectionString = string.Format("Data Source={0}", filename); foreach (var provider in SharpMap.Data.Providers.SpatiaLite.GetSpatialTables(connectionString)) { map.Layers.Add( new SharpMap.Layers.VectorLayer( string.Format("{0} - {1}", provider.Table, provider.GeometryColumn), provider) { Style = LayerTools.GetRandomVectorStyle() }); } } if (map.Layers.Count > 0) { map.ZoomToExtents(); System.Drawing.Drawing2D.Matrix mat = new System.Drawing.Drawing2D.Matrix(); mat.RotateAt(angle, map.WorldToImage(map.Center)); map.MapTransform = mat; return map; } } catch (System.Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } return null; }
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 ;-). }
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; }
public List<Point> ToPoints( float angle, Rectangle rect) { // Graphics g = Graphics.FromImage(this.Image); Graphics g = Graphics.FromHwnd(this.Handle); List<Point> source_points = new List<Point>(); source_points.Add(new Point(rect.X, rect.Y)); source_points.Add(new Point(rect.X + rect.Width, rect.Y)); source_points.Add(new Point(rect.X +rect.Width, rect.Y + rect.Height)); source_points.Add(new Point(rect.X, rect.Y + rect.Height)); Point[] pts = source_points.ToArray(); Rectangle display_rect = GetPictureBoxZoomSize(); float x_ratio = (float)display_rect.Width / (float)this.Image.Width; float y_ratio = (float)display_rect.Height / (float)this.Image.Height; System.Drawing.Drawing2D.Matrix rotateMatrix = new System.Drawing.Drawing2D.Matrix(); // Set the rotation angle and starting point for the text. rotateMatrix.RotateAt(angle, new PointF(this.Image.Width / 2, this.Image.Height / 2)); //rotateMatrix.RotateAt(angle, new PointF(0, 0)); g.MultiplyTransform(rotateMatrix); // g.ScaleTransform(x_ratio, y_ratio); // g.ScaleTransform((float)1.1, (float)1.1); // g.RotateTransform(angle); g.TransformPoints(System.Drawing.Drawing2D.CoordinateSpace.World, System.Drawing.Drawing2D.CoordinateSpace.Device, pts); return pts.ToList(); }
public void Draw2dTextures(Draw2dData[] todraw, int textureid, float angle) { GL.PushAttrib(AttribMask.ColorBufferBit); GL.BindTexture(TextureTarget.Texture2D, textureid); GL.Enable(EnableCap.Texture2D); GL.Disable(EnableCap.DepthTest); VertexPositionTexture[] vertices; ushort[] indices; if (todraw.Length >= draw2dtexturesMAX) { vertices = new VertexPositionTexture[todraw.Length * 4]; indices = new ushort[todraw.Length * 4]; } else { if (draw2dtexturesVertices == null) { draw2dtexturesVertices = new VertexPositionTexture[draw2dtexturesMAX * 4]; draw2dtexturesIndices = new ushort[draw2dtexturesMAX * 4]; } vertices = draw2dtexturesVertices; indices = draw2dtexturesIndices; } ushort i = 0; foreach (Draw2dData v in todraw) { RectangleF rect; if (v.inAtlasId == null) { rect = new RectangleF(0, 0, 1, 1); } else { rect = TextureAtlas.TextureCoords2d(v.inAtlasId.Value, d_Terrain.texturesPacked); } float x2 = v.x1 + v.width; float y2 = v.y1 + v.height; PointF[] pnts = new PointF[4] { new PointF(x2, y2), new PointF(x2,v.y1), new PointF(v.x1,v.y1), new PointF(v.x1,y2)}; if (angle != 0) { System.Drawing.Drawing2D.Matrix mx=new System.Drawing.Drawing2D.Matrix(); mx.RotateAt(angle, new PointF(v.x1+v.width/2,v.y1+v.height/2)); mx.TransformPoints(pnts); } vertices[i] = new VertexPositionTexture(pnts[0].X, pnts[0].Y, 0, rect.Right, rect.Bottom, v.color); vertices[i + 1] = new VertexPositionTexture(pnts[1].X, pnts[1].Y, 0, rect.Right, rect.Top, v.color); vertices[i + 2] = new VertexPositionTexture(pnts[2].X, pnts[2].Y, 0, rect.Left, rect.Top, v.color); vertices[i + 3] = new VertexPositionTexture(pnts[3].X, pnts[3].Y, 0, rect.Left, rect.Bottom, v.color); indices[i] = i; indices[i + 1] = (ushort)(i + 1); indices[i + 2] = (ushort)(i + 2); indices[i + 3] = (ushort)(i + 3); i += 4; } GL.EnableClientState(ArrayCap.TextureCoordArray); GL.EnableClientState(ArrayCap.VertexArray); GL.EnableClientState(ArrayCap.ColorArray); unsafe { fixed (VertexPositionTexture* p = vertices) { GL.VertexPointer(3, VertexPointerType.Float, StrideOfVertices, (IntPtr)(0 + (byte*)p)); GL.TexCoordPointer(2, TexCoordPointerType.Float, StrideOfVertices, (IntPtr)(12 + (byte*)p)); GL.ColorPointer(4, ColorPointerType.UnsignedByte, StrideOfVertices, (IntPtr)(20 + (byte*)p)); GL.DrawElements(BeginMode.Quads, i, DrawElementsType.UnsignedShort, indices); } } GL.DisableClientState(ArrayCap.TextureCoordArray); GL.DisableClientState(ArrayCap.VertexArray); GL.DisableClientState(ArrayCap.ColorArray); GL.Enable(EnableCap.DepthTest); GL.PopAttrib(); }
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; } }
/// <summary> /// Draws a horizontal chart scale</summary> /// <param name="g">The Direct2D graphics object</param> /// <param name="transform">Graph (world) to window's client (screen) transform</param> /// <param name="graphRect">Graph rectangle</param> /// <param name="top">Whether or not the scale should be aligned along the top of the rectangle</param> /// <param name="majorSpacing">Spacing, in pixels, between major tick marks</param> /// <param name="minimumGraphStep">Minimum spacing, in graph (world) space, between ticks. /// For example, 1.0 would limit ticks to being drawn on whole integers.</param> /// <param name="lineBrush">Scale line pen</param> /// <param name="textFormat">Text format</param> /// <param name="textBrush">Text brush</param> public static void DrawHorizontalScale( this D2dGraphics g, Matrix transform, RectangleF graphRect, bool top, int majorSpacing, float minimumGraphStep, D2dBrush lineBrush, D2dTextFormat textFormat, D2dBrush textBrush) { double xScale = transform.Elements[0]; RectangleF clientRect = Transform(transform, graphRect); double tickEnd, majorTickStart, minorTickStart, textStart; if (top) { tickEnd = clientRect.Top + 1; majorTickStart = tickEnd + 12; minorTickStart = tickEnd + 6; textStart = tickEnd + 8; } else { tickEnd = clientRect.Bottom - 1; majorTickStart = tickEnd - 12; minorTickStart = tickEnd - 6; textStart = tickEnd - 19; } double min = Math.Min(graphRect.Left, graphRect.Right); double max = Math.Max(graphRect.Left, graphRect.Right); double tickAnchor = CalculateTickAnchor(min, max); double majorGraphStep = CalculateStep( min, max, Math.Abs(clientRect.Right - clientRect.Left), majorSpacing, minimumGraphStep); int numMinorTicks = CalculateNumMinorTicks(majorGraphStep, minimumGraphStep, 5); double cMinorStep = (majorGraphStep / numMinorTicks) * xScale; if (majorGraphStep > 0) { double offset = tickAnchor - min; offset = offset - MathUtil.Remainder(offset, majorGraphStep); // draw leading minor ticks double cmx; cmx = ((tickAnchor - (offset + majorGraphStep)) - min) * xScale + clientRect.Left + cMinorStep; for (int i = 0; i < numMinorTicks - 1 && cmx < clientRect.Right; i++) { // cull minor ticks outside of the view if (cmx > clientRect.Left) { g.DrawLine((float)cmx, (float)minorTickStart, (float)cmx, (float)tickEnd, lineBrush); } cmx += cMinorStep; } for (double x = tickAnchor - offset; x < max; x += majorGraphStep) { double cx = (x - min) * xScale + clientRect.Left; g.DrawLine((float)cx, (float)majorTickStart, (float)cx, (float)tickEnd, lineBrush); string xString = String.Format("{0:G8}", Math.Round(x, 6)); SizeF textSize = g.MeasureText(xString, textFormat); var textRect = new RectangleF(new PointF((float)cx + 1, (float)textStart), textSize); g.DrawText(xString, textFormat, textRect, textBrush); // draw minor ticks cmx = cx + cMinorStep; for (int i = 0; i < numMinorTicks - 1 && cmx < clientRect.Right; i++) { g.DrawLine((float)cmx, (float)minorTickStart, (float)cmx, (float)tickEnd, lineBrush); cmx += cMinorStep; } } } }
public static bool ConvertType(object value, Type targetType, out object result) { result = value; if (value == null) return true; if (value is string && targetType == typeof(Type)) { string typeName = (string)value; Type type; if (!_objectClassRegistrations.TryGetValue(typeName, out type)) type = Type.GetType(typeName); if (type != null) { result = type; return true; } } // Don't convert LateBoundValue (or superclass ValueWrapper) here... instances of // LateBoundValue must stay unchanged until some code part explicitly converts them! if (value is ResourceWrapper) { object resource = ((ResourceWrapper)value).Resource; if (TypeConverter.Convert(resource, targetType, out result)) { if (ReferenceEquals(resource, result)) { // Resource must be copied because setters and other controls most probably need a copy of the resource. // If we don't copy it, Setter is not able to check if we already return a copy because our input value differs // from the output value, even if we didn't do a copy here. result = MpfCopyManager.DeepCopyCutLVPs(result); } return true; } } if (value is string && targetType == typeof(FrameworkElement)) { // It doesn't suffice to have an implicit data template declaration which returns a label for a string. // If you try to build a ResourceWrapper with a string and assign that ResourceWrapper to a Button's Content property // with a StaticResource, for example, the ResourceWrapper will be assigned directly without the data template being // applied. To make it sill work, we need this explicit type conversion here. result = new Label { Content = (string)value, Color = Color.White }; return true; } if (targetType == typeof(Transform)) { string v = value.ToString(); string[] parts = v.Split(new[] { ',' }); if (parts.Length == 6) { float[] f = new float[parts.Length]; for (int i = 0; i < parts.Length; ++i) { object obj; TypeConverter.Convert(parts[i], typeof(double), out obj); f[i] = (float)obj; } System.Drawing.Drawing2D.Matrix matrix2D = new System.Drawing.Drawing2D.Matrix(f[0], f[1], f[2], f[3], f[4], f[5]); Static2dMatrix matrix = new Static2dMatrix(); matrix.Set2DMatrix(matrix2D); result = matrix; return true; } } else if (targetType == typeof(Vector2)) { result = Convert2Vector2(value.ToString()); return true; } else if (targetType == typeof(Vector3)) { result = Convert2Vector3(value.ToString()); return true; } else if (targetType == typeof(Vector4)) { result = Convert2Vector4(value.ToString()); return true; } else if (targetType == typeof(Thickness)) { Thickness t; float[] numberList = ParseFloatList(value.ToString()); if (numberList.Length == 1) { t = new Thickness(numberList[0]); } else if (numberList.Length == 2) { t = new Thickness(numberList[0], numberList[1]); } else if (numberList.Length == 4) { t = new Thickness(numberList[0], numberList[1], numberList[2], numberList[3]); } else { throw new ArgumentException("Invalid # of parameters"); } result = t; return true; } else if (targetType == typeof(Color)) { Color color; if (ColorConverter.ConvertColor(value, out color)) { result = color; return true; } } else if (targetType == typeof(Brush) && value is string || value is Color) { try { Color color; if (ColorConverter.ConvertColor(value, out color)) { SolidColorBrush b = new SolidColorBrush { Color = color }; result = b; return true; } } catch (Exception) { return false; } } else if (targetType == typeof(GridLength)) { string text = value.ToString(); if (text == "Auto") result = new GridLength(GridUnitType.Auto, 0.0); else if (text == "AutoStretch") result = new GridLength(GridUnitType.AutoStretch, 1.0); else if (text.IndexOf('*') >= 0) { int pos = text.IndexOf('*'); text = text.Substring(0, pos); if (text.Length > 0) { object obj; TypeConverter.Convert(text, typeof(double), out obj); result = new GridLength(GridUnitType.Star, (double)obj); } else result = new GridLength(GridUnitType.Star, 1.0); } else { double v = double.Parse(text); result = new GridLength(GridUnitType.Pixel, v); } return true; } else if (targetType == typeof(string) && value is IResourceString) { result = ((IResourceString)value).Evaluate(); return true; } else if (targetType.IsAssignableFrom(typeof(IExecutableCommand)) && value is ICommand) { result = new CommandBridge((ICommand)value); return true; } else if (targetType == typeof(Key) && value is string) { string str = (string)value; // Try a special key result = Key.GetSpecialKeyByName(str); if (result == null) if (str.Length != 1) throw new ArgumentException(string.Format("Cannot convert '{0}' to type Key", str)); else result = new Key(str[0]); return true; } else if (targetType == typeof(string) && value is IEnumerable) { result = StringUtils.Join(", ", (IEnumerable)value); return true; } result = value; return false; }
public PDFTransformationMatrix() { _matrix = new System.Drawing.Drawing2D.Matrix(); _matrix.Reset(); }
public static SharpMap.Map InitializeMap(float angle) { //Initialize a new map of size 'imagesize' SharpMap.Map map = new SharpMap.Map(); //Set up the countries layer SharpMap.Layers.VectorLayer layCountries = new SharpMap.Layers.VectorLayer("Countries"); //Set the datasource to a shapefile in the App_data folder layCountries.DataSource = new SharpMap.Data.Providers.SpatiaLite( DataSource, "countries", "geom", "PK_UID"); //Set fill-style to green layCountries.Style.Fill = new System.Drawing.SolidBrush(System.Drawing.Color.Green); //Set the polygons to have a black outline layCountries.Style.Outline = System.Drawing.Pens.Black; layCountries.Style.EnableOutline = true; //Set up a river layer SharpMap.Layers.VectorLayer layRivers = new SharpMap.Layers.VectorLayer("Rivers"); //Set the datasource to a shapefile in the App_data folder layRivers.DataSource = new SharpMap.Data.Providers.SpatiaLite( DataSource, "rivers", "geom", "PK_UID"); //Define a blue 3px wide pen layRivers.Style.Line = new System.Drawing.Pen(System.Drawing.Color.LightBlue, 2); layRivers.Style.Line.CompoundArray = new[] { 0.2f, 0.8f }; layRivers.Style.Outline = new System.Drawing.Pen(System.Drawing.Color.DarkBlue, 3); layRivers.Style.EnableOutline = true; //Set up a cities layer SharpMap.Layers.VectorLayer layCities = new SharpMap.Layers.VectorLayer("Cities"); //Set the datasource to the spatialite table layCities.DataSource = new SharpMap.Data.Providers.SpatiaLite( DataSource, "cities", "geom", "PK_UID"); layCities.Style.SymbolScale = 0.8f; layCities.MaxVisible = 40; //Set up a country label layer SharpMap.Layers.LabelLayer layLabel = new SharpMap.Layers.LabelLayer("Country labels") { DataSource = layCountries.DataSource, LabelColumn = "NAME", MultipartGeometryBehaviour = SharpMap.Layers.LabelLayer.MultipartGeometryBehaviourEnum.Largest, LabelFilter = SharpMap.Rendering.LabelCollisionDetection.ThoroughCollisionDetection, PriorityColumn = "POPDENS", Style = new SharpMap.Styles.LabelStyle { ForeColor = System.Drawing.Color.White, Font = new System.Drawing.Font(System.Drawing.FontFamily.GenericSerif, 12), BackColor = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(128, 255, 0, 0)), HorizontalAlignment = SharpMap.Styles.LabelStyle.HorizontalAlignmentEnum.Center, MaxVisible = 90, MinVisible = 30, CollisionDetection = true } }; //Set up a city label layer SharpMap.Layers.LabelLayer layCityLabel = new SharpMap.Layers.LabelLayer("City labels") { DataSource = layCities.DataSource, LabelColumn = "name", PriorityColumn = "population", PriorityDelegate = delegate(SharpMap.Data.FeatureDataRow fdr) { System.Int32 retVal = 10000000 * ( (System.String)fdr["capital"] == "Y" ? 1 : 0 ); return retVal + System.Convert.ToInt32(fdr["population"]); }, TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias, SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias, LabelFilter = SharpMap.Rendering.LabelCollisionDetection.ThoroughCollisionDetection, Style = new SharpMap.Styles.LabelStyle { ForeColor = System.Drawing.Color.Black, Font = new System.Drawing.Font(System.Drawing.FontFamily.GenericSerif, 11), MaxVisible = layLabel.MinVisible, HorizontalAlignment = SharpMap.Styles.LabelStyle.HorizontalAlignmentEnum.Left, VerticalAlignment = SharpMap.Styles.LabelStyle.VerticalAlignmentEnum.Bottom, Offset = new System.Drawing.PointF(3, 3), Halo = new System.Drawing.Pen(System.Drawing.Color.Yellow, 2), CollisionDetection = true } }; var layRiverLabels = new SharpMap.Layers.LabelLayer("RiverLabels"); layRiverLabels.DataSource = layRivers.DataSource; layRiverLabels.LabelColumn = "Name"; layRiverLabels.PriorityDelegate = GetRiverLength; layRiverLabels.Style = new SharpMap.Styles.LabelStyle { Font = new System.Drawing.Font("Arial", 10, System.Drawing.FontStyle.Bold), Halo = new System.Drawing.Pen(System.Drawing.Color.Azure, 2), ForeColor = System.Drawing.Color.DarkCyan, IgnoreLength = true, Enabled = true, CollisionDetection = true, }; layRiverLabels.LabelFilter = SharpMap.Rendering.LabelCollisionDetection.ThoroughCollisionDetection; //Add the layers to the map object. //The order we add them in are the order they are drawn, so we add the rivers last to put them on top map.Layers.Add(layCountries); map.Layers.Add(layRivers); map.Layers.Add(layCities); map.Layers.Add(layRiverLabels); map.Layers.Add(layLabel); map.Layers.Add(layCityLabel); //limit the zoom to 360 degrees width map.MaximumZoom = 360; map.BackColor = System.Drawing.Color.LightBlue; map.ZoomToExtents(); // = 360; //map.Center = new SharpMap.Geometries.Point(0, 0); var mat = new System.Drawing.Drawing2D.Matrix(); mat.RotateAt(angle, map.WorldToImage(map.Center)); map.MapTransform = mat; return map; }
// 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> /// Draw page and its children /// </summary> /// <param name="gc"></param> /// <param name="clipRect"></param> public void Draw(Graphics gc, Rectangle clipRect) { System.Drawing.Drawing2D.Matrix finalMatrix = new System.Drawing.Drawing2D.Matrix(); finalMatrix = this.drawMatrix.Clone(); finalMatrix.Multiply(this.ViewMatrix, System.Drawing.Drawing2D.MatrixOrder.Append); gc.Transform = finalMatrix; // draw fill color using (SolidBrush brush = new SolidBrush(fillColor)) { gc.FillRectangle(brush, 0, 0, (float)this.WidthInPixels, (float)this.HeightInPixels); } // draw background image if (pictureForDisplay != null) { gc.DrawImage(pictureForDisplay, 0, 0, (float)this.WidthInPixels, (float)this.HeightInPixels); } this.LastDrawMatrix = finalMatrix; EditorController.Instance.Grid.Draw(gc); foreach(EditorItem item in Children) { item.Draw(this.ViewMatrix, gc, clipRect); } // draw item commands foreach (EditorItem child in Children) { child.DrawCommands((float)this.ZoomLevel / 100, gc); } }
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()); } }
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; }
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()); } }
/// <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(); }
public Bitmap MakeGraph(float _xmin, float _xmax, float _ymin, float _ymax) { //The bounds to draw. xmin = _xmin; xmax = _xmax; ymin = _ymin; ymax = _ymax; // Make the Bitmap. gr = Graphics.FromImage(bitmapFunction); gr.Clear(Color.Transparent); gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; //Transform the graphics object to cartesian coordinates float fdx = wid * -(xmin / (xmax - xmin)); float fdy = hgt * -(ymax / (ymin - ymax)); gr.TranslateTransform(fdx, fdy); float sx = Convert.ToSingle(wid) / Math.Abs(xmax - xmin); float sy = Convert.ToSingle(hgt) / Math.Abs(ymax - ymin); gr.ScaleTransform(sx, -sy); // Draw the graph. using (Pen graph_pen = new Pen(Color.Blue, 0), grid_pen = new Pen(Color.LightGray, 0)) { for (int x = (int)xmin; x <= xmax; x++) { //Draw Grid gr.DrawLine(grid_pen, x, ymin, x, ymax); //Draw AxesSeperation gr.DrawLine(graph_pen, x, -0.1f, x, 0.1f); } for (int y = (int)ymin; y <= ymax; y++) { //Draw Grid gr.DrawLine(grid_pen, xmin, y, xmax, y); //Draw AxesSeperation gr.DrawLine(graph_pen, -0.1f, y, 0.1f, y); } //Draw the axes. gr.DrawLine(graph_pen, xmin, 0, xmax, 0); gr.DrawLine(graph_pen, 0, ymin, 0, ymax); graph_pen.Color = Color.Red; //See how big 1 pixel is horizontally. System.Drawing.Drawing2D.Matrix inverse = gr.Transform; inverse.Invert(); PointF[] pixel_pts = { new PointF(0, 0), new PointF(1, 0) }; inverse.TransformPoints(pixel_pts); float dx = pixel_pts[1].X - pixel_pts[0].X; dx /= 4; //Draw Function //Loop over every function in DataGridView for (int i = 0; i < dataGridView.RowCount - 1; i++) { if (dataGridView.Rows[i].Selected == true) { float y; //Loop over x values to generate points. for (float x = xmin; x <= xmax; x += dx) { //Get the next point. y = function(x, i); if (!Single.IsNaN(y) && !Single.IsInfinity(y) && !(y > 100000)) { //Only add points that are visible if (y < ymax + 0.2 && ymin - 0.2 < y) { if (function(x - dx, i) > ymax || function(x - dx, i) < ymin) { pointsFunction.Add(new PointF(x - dx, function(x - dx, i))); } pointsFunction.Add(new PointF(x, y)); if (function(x + dx, i) > ymax || function(x + dx, i) < ymin) { pointsFunction.Add(new PointF(x + dx, function(x + dx, i))); } } } } if (pointsFunction.Count != 0) { try { gr.DrawLines(graph_pen, pointsFunction.ToArray()); } catch (Exception e) { MessageBox.Show(e.ToString(), e.Message); } } pointsFunction.Clear(); } } } controller.UpdateFunctionTextBox(xmin, xmax, ymin, ymax); //return the result. return(DrawVisualization()); }
/// <summary> /// Transforms rectangle</summary> /// <param name="matrix">Matrix representing transform</param> /// <param name="r">Rectangle</param> /// <returns>Transformed rectangle</returns> public static RectangleF Transform(Matrix matrix, RectangleF r) { s_tempPtsF[0] = new PointF(r.Left, r.Top); s_tempPtsF[1] = new PointF(r.Right, r.Bottom); matrix.TransformPoints(s_tempPtsF); return MakeRectangle(s_tempPtsF[0], s_tempPtsF[1]); }
protected PDFTransformationMatrix(System.Drawing.Drawing2D.Matrix innerMatrix) { this._matrix = innerMatrix; }
public static SharpMap.Map InitializeMap(float angle) { using (var ofn = new System.Windows.Forms.OpenFileDialog()) { ofn.Filter = "All files|*.*"; ofn.FilterIndex = 0; if (ofn.ShowDialog() == System.Windows.Forms.DialogResult.OK) { var m = new SharpMap.Map(); var l = new SharpMap.Layers.GdiImageLayer(ofn.FileName); m.Layers.Add(l); m.ZoomToExtents(); var mat = new System.Drawing.Drawing2D.Matrix(); mat.RotateAt(angle, m.WorldToImage(m.Center)); m.MapTransform = mat; m.MaximumExtents = m.GetExtents(); m.EnforceMaximumExtents = true; return m; } } return null; }