/// <summary> /// 画像をピクチャボックスのサイズに合わせて全体に表示するアフィン変換行列を求める /// </summary> /// <param name="mat">アフィン変換行列</param> /// <param name="image">画像データ</param> /// <param name="dst">描画先のピクチャボックス</param> private void ZoomFit( ref System.Drawing.Drawing2D.Matrix mat, ImagingSolution.Imaging.ImageData image, PictureBox dst) { // アフィン変換行列の初期化(単位行列へ) mat.Reset(); int srcWidth = image.Width; int srcHeight = image.Height; int dstWidth = dst.Width; int dstHeight = dst.Height; float scale; // 縦に合わせるか?横に合わせるか? if (srcHeight * dstWidth > dstHeight * srcWidth) { // ピクチャボックスの縦方法に画像表示を合わせる場合 scale = dstHeight / (float)srcHeight; mat.Scale(scale, scale, System.Drawing.Drawing2D.MatrixOrder.Append); // 中央へ平行移動 mat.Translate((dstWidth - srcWidth * scale) / 2f, 0f, System.Drawing.Drawing2D.MatrixOrder.Append); } else { // ピクチャボックスの横方法に画像表示を合わせる場合 scale = dstWidth / (float)srcWidth; mat.Scale(scale, scale, System.Drawing.Drawing2D.MatrixOrder.Append); // 中央へ平行移動 mat.Translate(0f, (dstHeight - srcHeight * scale) / 2f, System.Drawing.Drawing2D.MatrixOrder.Append); } }
public PDFTransformationMatrix(float offsetX, float offsetY, float angle, float scaleX, float scaleY) : this() { _matrix.Translate(offsetX, offsetY); _matrix.Rotate(angle); _matrix.Scale(scaleX, scaleY); }
// マウスホイールイベント private void PictureBox1_MouseWheel(object sender, MouseEventArgs e) { var _cursor = this.Cursor; this.Cursor = Cursors.SizeAll; // ポインタの位置→原点へ移動 DrawMatrix.Translate(-e.X, -e.Y, System.Drawing.Drawing2D.MatrixOrder.Append); if (e.Delta > 0) { // 拡大 if (DrawMatrix.Elements[0] < 100) // X方向の倍率を代表してチェック { DrawMatrix.Scale(1.5f, 1.5f, System.Drawing.Drawing2D.MatrixOrder.Append); } } else { // 縮小 if (DrawMatrix.Elements[0] > 0.01) // X方向の倍率を代表してチェック { DrawMatrix.Scale(1.0f / 1.5f, 1.0f / 1.5f, System.Drawing.Drawing2D.MatrixOrder.Append); } } // 原点→ポインタの位置へ移動(元の位置へ戻す) DrawMatrix.Translate(e.X, e.Y, System.Drawing.Drawing2D.MatrixOrder.Append); // 画像の描画 DrawImage(); this.Cursor = _cursor; }
public void MouseWheelPictureBox(object sender, MouseEventArgs e) { Control eventCtrl = (Control)sender; /*各ディクショナリからコントロール名をキーに値を取得(値の変更がある場合、別途コミットが必要)*/ System.Drawing.Drawing2D.Matrix targetMat = dicMat[eventCtrl.Name]; //ポインタの位置→原点へ移動 targetMat.Translate(-e.X, -e.Y, System.Drawing.Drawing2D.MatrixOrder.Append); if (e.Delta > 0) { //拡大 if (targetMat.Elements[0] < 100) //X方向の倍率を代表してチェック { targetMat.Scale(1.5f, 1.5f, System.Drawing.Drawing2D.MatrixOrder.Append); } } else { //縮小 if (targetMat.Elements[0] > 0.01) //X方向の倍率を代表してチェック { targetMat.Scale(1.0f / 1.5f, 1.0f / 1.5f, System.Drawing.Drawing2D.MatrixOrder.Append); } } //原点→ポインタの位置へ移動(元の位置へ戻す) targetMat.Translate(e.X, e.Y, System.Drawing.Drawing2D.MatrixOrder.Append); //画像の描画 DrawImage(eventCtrl); }
public void DrawString(Graphics graphics, string text, float fontSize, string fontEmphasis, string fontWeight, Brush brush, PointF point) { var x = point.X; var y = point.Y; var letterSpacing = 0.01f; foreach (var c in text) { var g = GetGlyph(fontWeight, fontEmphasis, c.ToString()); if (g != null) { var p = PathConverter.ConvertPath(new SVG.Path() { Commands = g.PathCommands }); var m = new System.Drawing.Drawing2D.Matrix(); var sf = fontSize / 20.0f; m.Scale(sf, sf); m.Translate(x / sf, y / sf + 25f); p.Transform(m); graphics.FillPath(brush, p); x += g.Width * sf + letterSpacing * fontSize * sf; } } }
/// <summary> Scales the current transformation matrix by the given /// amount. /// /// </summary> /// <param name="x">x coordinate of the Scale factor /// </param> /// <param name="y">y coordinate of the Scale factor /// </param> public virtual void Scale(double x, double y) { System.Drawing.Drawing2D.Matrix temp_Matrix; temp_Matrix = new System.Drawing.Drawing2D.Matrix(); temp_Matrix.Scale((float)x, (float)y); transform(temp_Matrix); }
public override void ApplyTransformation(System.Drawing.Drawing2D.Matrix transform) { transform.Reset(); if (fromScale != toScale) { if (small2Big) { curScale += CHANGE_VALUE; if (curScale >= toScale) { curScale = toScale; small2Big = false; repeatCount++; } } else { curScale -= CHANGE_VALUE; if (curScale <= fromScale) { curScale = fromScale; small2Big = true; } } offsetX = pivotX * curScale - pivotX; offsetY = pivotY * curScale - pivotY; transform.Translate(-offsetX, -offsetY); transform.Scale(curScale, curScale); } }
public void scaleCurentFigure() { System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix(); System.Drawing.Drawing2D.Matrix test = new System.Drawing.Drawing2D.Matrix(1, 0, 0, 1, 0, 0); // трансформация из double[,] в pointF[] System.Drawing.PointF[] arr = new System.Drawing.PointF[rank]; for (int i = 0; i < mainPoins2.Length; i++) { arr[i] = new System.Drawing.PointF((float)mainPoins2[i].X, (float)mainPoins2[i].Y); } // увеличение matrix.Scale(50, 50); // применение увеличения // matrix.Shear(-2, -2); matrix.TransformPoints(arr); // уже увеличеная фигура (точки) for (int i = 0; i < mainPoins2.Length; i++) { // arr[i] = new System.Drawing.PointF((float)mainPoins2[i].X, (float)mainPoins2[i].Y); mainPoins2[i].X = arr[i].X; mainPoins2[i].Y = arr[i].Y; } // setPointFToLinearr(arr); }
private void MirrorPath(System.Drawing.Drawing2D.GraphicsPath GraphicPath) { System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix(); m.Translate(0, Height - 1); m.Scale(1, -1); GraphicPath.Transform(m); m.Dispose(); }
protected virtual void SetTransform(System.Drawing.Drawing2D.Matrix transform, float scale) { offsetX = pivotX * scale - pivotX; offsetY = pivotY * scale - pivotY; transform.Translate(-offsetX, -offsetY); transform.Scale(scale, scale); }
public override void ApplyTransformation(System.Drawing.Drawing2D.Matrix transform) { base.ApplyTransformation(transform); float scale = GetScale(curX); offsetX = width * scale - width; transform.Translate(-offsetX, 0); transform.Scale(GetScale(curX), 1); }
private void Dialogs_MouseMove(object sender, MouseEventArgs e) { if (movestart == null) { return; } if (FocusedPhrase == -1 && FocusedTimeline == -1 && !TranslateFocus) { return; } System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix(); //m.Translate(Translate.X, Translate.Y, System.Drawing.Drawing2D.MatrixOrder.Append); m.Scale(ScaleZoom, ScaleZoom, System.Drawing.Drawing2D.MatrixOrder.Append); m.Invert(); Point movement = new Point(movestart.X - e.X, movestart.Y - e.Y); movement.X = -movement.X; movement.Y = -movement.Y; Point[] t = new Point[] { movement }; m.TransformPoints(t); movement = t[0]; if (FocusedPhrase != -1) { if (TreeOperationMode) { dlg.MovePhraseTree(FocusedPhrase, movement); } else { dlg.MovePhrase(FocusedPhrase, movement); } Changed = true; } else if (FocusedTimeline >= 0) { Point x = new Point(0, dlginstance.Timeline(FocusedTimeline).Ylocation); x.Offset(movement); dlginstance.Timeline(FocusedTimeline).Ylocation = x.Y; Changed = true; } else { Translate.X -= movestart.X - e.X; Translate.Y -= movestart.Y - e.Y; //Translate.Offset(movement); } movestart = e.Location; this.Refresh(); }
public override void ApplyTransformation(System.Drawing.Drawing2D.Matrix transform) { stepCount++; float scale = 1 - 0.2f * (stepCount - 1); float offset = pivotY * scale - pivotY; transform.Reset(); transform.Translate(0, -offset); transform.Scale(1, scale); }
/// <summary> /// 指定した点を中心に拡大縮小するアフィン変換行列の計算 /// </summary> /// <param name="mat">アフィン変換行列</param> /// <param name="scale">拡大縮小の倍率</param> /// <param name="center">拡大縮小の中心座標</param> public static void ScaleAt(this System.Drawing.Drawing2D.Matrix mat, float scale, PointF center) { // 原点へ移動 mat.Translate(-center.X, -center.Y, System.Drawing.Drawing2D.MatrixOrder.Append); // 拡大縮小 mat.Scale(scale, scale, System.Drawing.Drawing2D.MatrixOrder.Append); // 元へ戻す mat.Translate(center.X, center.Y, System.Drawing.Drawing2D.MatrixOrder.Append); }
private static void TransformContents(List <Shape> contents, Transaction transaction, bool changingDocument, Rectangle newRect, Rectangle oldRect) { System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix(); if (!changingDocument) { matrix.Translate(-oldRect.X, -oldRect.Y, System.Drawing.Drawing2D.MatrixOrder.Append); matrix.Scale((float)newRect.Width / oldRect.Width, (float)newRect.Height / oldRect.Height, System.Drawing.Drawing2D.MatrixOrder.Append); matrix.Translate(newRect.X, newRect.Y, System.Drawing.Drawing2D.MatrixOrder.Append); } else { matrix.Scale((float)newRect.Width / oldRect.Width, (float)newRect.Height / oldRect.Height, System.Drawing.Drawing2D.MatrixOrder.Append); } Transformation transform = new TransformAffine(Transformation.Modes.Move, matrix); foreach (Shape shape in contents) { transaction.Edit(shape); shape.ApplyTransformation(transform); } }
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)); } }
public void scale_ink(float scale) { if (!Component.BARTPE && !Component.VM && !Component.MONO) { float f; System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix(); this.tab_overlay.Renderer.SetViewTransform(matrix); f = (float)((float)(Visual_Flow_Form.flow_width + 5) * ink_resolution); matrix.Translate(f, (float)0.0); matrix.Scale(scale, scale); this.tab_overlay.Renderer.SetViewTransform(matrix); } }
/// <summary> /// 画像をピクチャボックスに合わせて表示するアフィン変換行列の計算(拡張メソッド) /// </summary> /// <param name="mat">アフィン変換行列</param> /// <param name="pic">描画先のピクチャボックス</param> /// <param name="bmp">描画するBitmapオブジェクト</param> public static void ZoomFit(this System.Drawing.Drawing2D.Matrix mat, PictureBox pic, Bitmap bmp) { if (bmp == null) { return; } // アフィン変換行列の初期化(単位行列へ) mat.Reset(); // 0.5画素分移動 mat.Translate(0.5f, 0.5f, System.Drawing.Drawing2D.MatrixOrder.Append); int srcWidth = bmp.Width; int srcHeight = bmp.Height; int dstWidth = pic.Width; int dstHeight = pic.Height; float scale; // 縦に合わせるか?横に合わせるか? if (srcHeight * dstWidth > dstHeight * srcWidth) { // ピクチャボックスの縦方法に画像表示を合わせる場合 scale = dstHeight / (float)srcHeight; mat.Scale(scale, scale, System.Drawing.Drawing2D.MatrixOrder.Append); // 中央へ平行移動 mat.Translate((dstWidth - srcWidth * scale) / 2f, 0f, System.Drawing.Drawing2D.MatrixOrder.Append); } else { // ピクチャボックスの横方法に画像表示を合わせる場合 scale = dstWidth / (float)srcWidth; mat.Scale(scale, scale, System.Drawing.Drawing2D.MatrixOrder.Append); // 中央へ平行移動 mat.Translate(0f, (dstHeight - srcHeight * scale) / 2f, System.Drawing.Drawing2D.MatrixOrder.Append); } }
protected void ExportBracketExpression(Graphics graphics, BracketExpression bracketExpression) { ExportElement(graphics, bracketExpression.InnerExpression); var g1 = _fontLoader.GetGlyph("normal", "none", "("); var g2 = _fontLoader.GetGlyph("normal", "none", ")"); var w = g1.Width; var h = bracketExpression.InnerExpression.OuterHeight; var x1 = (float)(bracketExpression.Position.X.Quantity); var y1 = (float)bracketExpression.Position.Y.Quantity; var x2 = (float)(bracketExpression.Position.X.Quantity + bracketExpression.InnerExpression.OuterWidth.Quantity); var y2 = (float)bracketExpression.Position.Y.Quantity; var p1 = PathConverter.ConvertPath(new Path() { Commands = g1.PathCommands }); // Paths.GetBracketPath(new PointF(, , (float)h.Quantity); var p2 = PathConverter.ConvertPath(new Path() { Commands = g2.PathCommands }); // Paths.GetBracketPath(new PointF(, ), (float)h.Quantity, ")"); var m1 = new System.Drawing.Drawing2D.Matrix(); var m2 = new System.Drawing.Drawing2D.Matrix(); var sf = (float)h.Quantity / (1.7f * 20.0f); m1.Scale(sf, sf); m1.Translate(x1 / sf, y1 / sf + 25f); m2.Scale(sf, sf); m2.Translate(x2 / sf, y2 / sf + 25f); p1.Transform(m1); p2.Transform(m2); graphics.FillPath(Brushes.Black, p1); graphics.FillPath(Brushes.Black, p2); if (bracketExpression.DrawConstructionLines == true) { DrawConstructionLines(graphics, bracketExpression.Position, bracketExpression.SizeIncludingOuterMargin); } }
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; }
/// <summary> /// 指定した点(point)周りの拡大縮小 /// </summary> /// <param name="scale">倍率</param> /// <param name="point">基準点の座標</param> private void ScaleAt( ref System.Drawing.Drawing2D.Matrix mat, float scale, PointF point ) { // 原点へ移動 mat.Translate(-point.X, -point.Y, System.Drawing.Drawing2D.MatrixOrder.Append); // 拡大縮小 mat.Scale(scale, scale, System.Drawing.Drawing2D.MatrixOrder.Append); // 元へ戻す mat.Translate(point.X, point.Y, System.Drawing.Drawing2D.MatrixOrder.Append); }
private void DrawInternal(System.Drawing.Graphics g, ICoordinateMapper coordinateMapper, System.Drawing.Rectangle renderingRect) { System.Drawing.Region oldClip = g.Clip; g.SetClip(renderingRect); System.Drawing.Drawing2D.Matrix oldMatrix = (System.Drawing.Drawing2D.Matrix)g.Transform.Clone(); try { if (_rect.DrawMode == VObjectDrawMode.Normal) { g.SmoothingMode = normalSmoothingMode; g.InterpolationMode = normalInterpolationMode; } else { g.SmoothingMode = draftSmoothingMode; g.InterpolationMode = draftInterpolationMode; } System.Drawing.RectangleF bounds = _rect.GetVObjectBounds(); System.Drawing.RectangleF transformedBounds = _rect.GetTransformedVObjectBounds(); System.Drawing.Rectangle mappedBounds = coordinateMapper.WorkspaceToControl(transformedBounds, Aurigma.GraphicsMill.Unit.Point); if (transformedBounds.Width > VObject.Eps && transformedBounds.Height > VObject.Eps) { float scaleX = mappedBounds.Width / transformedBounds.Width, scaleY = mappedBounds.Height / transformedBounds.Height; using (System.Drawing.Drawing2D.Matrix outputMatrix = (System.Drawing.Drawing2D.Matrix)_rect.Transform.Clone()) { outputMatrix.Translate(-transformedBounds.X, -transformedBounds.Y, System.Drawing.Drawing2D.MatrixOrder.Append); outputMatrix.Scale(scaleX, scaleY, System.Drawing.Drawing2D.MatrixOrder.Append); outputMatrix.Translate(mappedBounds.X, mappedBounds.Y, System.Drawing.Drawing2D.MatrixOrder.Append); g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; g.Transform = outputMatrix; g.DrawImage(this.DrawnImage, 0, 0, bounds.Width, bounds.Height); } } } finally { g.Transform = oldMatrix; g.SetClip(oldClip, System.Drawing.Drawing2D.CombineMode.Replace); } }
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; }
private void WidgetLayoutControl_Paint(object sender, PaintEventArgs e) { try { var g = e.Graphics; g.FillRectangle(SystemBrushes.Window, e.ClipRectangle); var matrix = new System.Drawing.Drawing2D.Matrix(); matrix.Translate(_displayOffset.X, _displayOffset.Y); matrix.Scale(_displayScale, _displayScale); g.Transform = matrix; var screenList = new ScreenList(); foreach (var screen in screenList) { using (var brush = GraphicsUtil.CreateRadialGradientBrush(screen.Bounds, Color.Blue, Color.Navy)) { g.FillRectangle(brush, screen.Bounds); } } foreach (var widget in _widgets) { var args = new WidgetDrawArgs(widget.Config, widget.Bounds, g, null, true); g.SetClip(widget.Bounds); widget.Draw(args); g.ResetClip(); } foreach (var screen in screenList) { g.DrawRectangle(SystemPens.ControlDarkDark, screen.Bounds); } g.Transform = new System.Drawing.Drawing2D.Matrix(); DrawSelectedWidgetBorder(g); } catch (Exception ex) { this.ShowError(ex); } }
private void AcceptScreenConfiguration() { SlideView view = this.mySlideView; //For some reason, this caused a hang if script data was preloaded. // for now we just assume it's always 1.3333. The assignment caused the // aspect ration to go from 1.333337 to 1.3333. //view.AspectRatio = (float)screenConfiguration.AspectRatio; System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix(); m.Scale(1 / (float)screenConfiguration.SlideSize, 1 / (float)screenConfiguration.SlideSize); foreach (SlideViewLayer layer in this.FetchLayersOfType(view, typeof(SlideViewLayer))) { layer.Transform = m; } m.Dispose(); }
internal static System.Drawing.Drawing2D.Matrix AdaptBrushToViewport(System.Drawing.Brush brush, Aurigma.GraphicsMill.WinControls.ICoordinateMapper coordinateMapper) { System.Drawing.Drawing2D.Matrix originalMatrix = null; if (brush != null && brush.GetType() != typeof(System.Drawing.SolidBrush) && brush.GetType() != typeof(System.Drawing.Drawing2D.HatchBrush)) { originalMatrix = VObjectsUtils.GetBrushMatrix(brush); System.Drawing.Point viewportTranslation = coordinateMapper.WorkspaceToControl(System.Drawing.PointF.Empty, Aurigma.GraphicsMill.Unit.Pixel); float scale = coordinateMapper.GetControlPixelsPerUnitX(Aurigma.GraphicsMill.Unit.Point); System.Drawing.Drawing2D.Matrix brushMatrix = new System.Drawing.Drawing2D.Matrix(); brushMatrix.Scale(scale, scale, System.Drawing.Drawing2D.MatrixOrder.Append); brushMatrix.Translate(viewportTranslation.X, viewportTranslation.Y, System.Drawing.Drawing2D.MatrixOrder.Append); brushMatrix.Multiply(originalMatrix, System.Drawing.Drawing2D.MatrixOrder.Prepend); VObjectsUtils.SetBrushMatrix(brush, brushMatrix); } return(originalMatrix); }
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; }
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]); }
protected void AdaptBrushToViewport(ICoordinateMapper coordinateMapper) { if (coordinateMapper == null) { throw new System.ArgumentNullException("coordinateMapper"); } if (_brush != null && _brush.GetType() != typeof(System.Drawing.SolidBrush) && _brush.GetType() != typeof(System.Drawing.Drawing2D.HatchBrush)) { System.Drawing.Drawing2D.Matrix originalMatrix = VObjectsUtils.GetBrushMatrix(_brush); _brushMatrices.Push(originalMatrix); System.Drawing.Point viewportTranslation = coordinateMapper.WorkspaceToControl(System.Drawing.PointF.Empty, Aurigma.GraphicsMill.Unit.Pixel); float scale = coordinateMapper.GetControlPixelsPerUnitX(Aurigma.GraphicsMill.Unit.Point); System.Drawing.Drawing2D.Matrix brushMatrix = (System.Drawing.Drawing2D.Matrix)_matrix.Clone(); brushMatrix.Scale(scale, scale, System.Drawing.Drawing2D.MatrixOrder.Append); brushMatrix.Translate(viewportTranslation.X, viewportTranslation.Y, System.Drawing.Drawing2D.MatrixOrder.Append); brushMatrix.Multiply(originalMatrix, System.Drawing.Drawing2D.MatrixOrder.Prepend); VObjectsUtils.SetBrushMatrix(_brush, brushMatrix); } }
private System.Drawing.Drawing2D.GraphicsPath CreateViewportPath(ICoordinateMapper coordinateMapper) { System.Drawing.Drawing2D.GraphicsPath result = (System.Drawing.Drawing2D.GraphicsPath) this.Path.Clone(); result.Transform(_matrix); System.Drawing.RectangleF pathBounds = this.Path.GetBounds(_matrix); System.Drawing.Rectangle mappedBounds = coordinateMapper.WorkspaceToControl(pathBounds, Aurigma.GraphicsMill.Unit.Point); if (pathBounds.Width > VObject.Eps && pathBounds.Height > VObject.Eps) { float scaleX = (float)mappedBounds.Width / pathBounds.Width, scaleY = (float)mappedBounds.Height / pathBounds.Height; using (System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix()) { m.Translate(mappedBounds.X, mappedBounds.Y); m.Scale(scaleX, scaleY); m.Translate(-pathBounds.X, -pathBounds.Y); result.Transform(m); } } return(result); }
void DrawOutput() { if (_g == null) { return; } //----------- //for GDI+ only bool drawInvert = chkInvert.Checked; int viewHeight = this.pnlGlyph.Height; //----------- //show tess _g.Clear(Color.White); int[] contourEndIndices; float[] polygon1 = GetPolygonData(out contourEndIndices); if (polygon1 == null) { return; } // if (drawInvert) { var transformMat = new System.Drawing.Drawing2D.Matrix(); transformMat.Scale(1, -1); transformMat.Translate(0, -viewHeight); // polygon1 = TransformPoints(polygon1, transformMat); } using (Pen pen1 = new Pen(Color.LightGray, 6)) { int nn = polygon1.Length; int a = 0; PointF p0; PointF p1; int contourCount = contourEndIndices.Length; int startAt = 3; for (int cnt_index = 0; cnt_index < contourCount; ++cnt_index) { int endAt = contourEndIndices[cnt_index]; for (int m = startAt; m <= endAt;) { p0 = new PointF(polygon1[m - 3], polygon1[m - 2]); p1 = new PointF(polygon1[m - 1], polygon1[m]); _g.DrawLine(pen1, p0, p1); _g.DrawString(a.ToString(), this.Font, Brushes.Black, p0); m += 2; a++; } //close contour p0 = new PointF(polygon1[endAt - 1], polygon1[endAt]); p1 = new PointF(polygon1[startAt - 3], polygon1[startAt - 2]); _g.DrawLine(pen1, p0, p1); _g.DrawString(a.ToString(), this.Font, Brushes.Black, p0); // startAt = (endAt + 1) + 3; } } if (!_tessTool.TessPolygon(polygon1, _contourEnds)) { return; } //1. List <ushort> indexList = _tessTool.TessIndexList; //2. List <TessVertex2d> tempVertexList = _tessTool.TempVertexList; //3. int vertexCount = indexList.Count; //----------------------------- int orgVertexCount = polygon1.Length / 2; float[] vtx = new float[vertexCount * 2];//*** int n = 0; for (int p = 0; p < vertexCount; ++p) { ushort index = indexList[p]; if (index >= orgVertexCount) { //extra coord (newly created) TessVertex2d extraVertex = tempVertexList[index - orgVertexCount]; vtx[n] = (float)extraVertex.x; vtx[n + 1] = (float)extraVertex.y; } else { //original corrd vtx[n] = (float)polygon1[index * 2]; vtx[n + 1] = (float)polygon1[(index * 2) + 1]; } n += 2; } //----------------------------- //draw tess result int j = vtx.Length; for (int i = 0; i < j;) { var p0 = new PointF(vtx[i], vtx[i + 1]); var p1 = new PointF(vtx[i + 2], vtx[i + 3]); var p2 = new PointF(vtx[i + 4], vtx[i + 5]); _g.DrawLine(Pens.Red, p0, p1); _g.DrawLine(Pens.Red, p1, p2); _g.DrawLine(Pens.Red, p2, p0); i += 6; } }
/// <summary> /// Paints the elements to the backbuffer /// </summary> private void UpdateBackBuffer() { _backBuffer = new Bitmap(Width, Height); Graphics graph = Graphics.FromImage(_backBuffer); graph.SmoothingMode = _drawingQuality; graph.FillRectangle(Brushes.White, 0, 0, _backBuffer.Width, _backBuffer.Height); //When the backbuffer is updated this code draws the watermark if (_showWaterMark) { Bitmap watermark = Images.MapWindowLogoPale; if ((_backBuffer.Width > watermark.Width) && (_backBuffer.Height > watermark.Height)) { graph.DrawImage(watermark, _backBuffer.Width - watermark.Width - 18, _backBuffer.Height - watermark.Height -18 ,watermark.Width , watermark.Height); } } //Check if there are any model elements to draw foreach (ModelElement me in _modelElements) { if (_modelElementsSelected.Contains(me) == false) { System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix(); Point translator = VirtualToPixel(new Point(me.Location.X, me.Location.Y)); m.Translate(translator.X,translator.Y); m.Scale(_virtualZoom, _virtualZoom); graph.Transform = m; me.Paint(graph); graph.Transform = new System.Drawing.Drawing2D.Matrix(); } } //Updates is initialized IsInitialized = true; }
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 void MapRenderer_Paint(object sender, PaintEventArgs e) { if (Map == null || backBuffer == null) return; RenderToBackBuffer(); e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix(); matrix.Scale(scale, scale); e.Graphics.Transform = matrix; e.Graphics.DrawImage(backBuffer, new PointF(-offsetX % Chunk.CHUNKSIZE_X, -offsetY % Chunk.CHUNKSIZE_Y)); // e.Graphics.DrawImage(backBuffer, new Point()); e.Graphics.Transform = new System.Drawing.Drawing2D.Matrix(); e.Graphics.DrawLine(Pens.Red, new Point(-(int)(offsetX * scale), 0), new Point(-(int)(offsetX * scale), ClientSize.Height)); e.Graphics.DrawLine(Pens.Red, new Point(0, -(int)(offsetY * scale)), new Point(ClientSize.Width, -(int)(offsetY * scale))); }
protected override bool InitializeTransformMatrix() { using (MethodLogger ml = new MethodLogger(this)) { if (!CheckGraphSanity()) { return false; } if (this.GraphRectangle.Height > 0) { minValue = float.MaxValue; maxValue = float.MinValue; this.CurveList.GetMinMax(0, dateSerie.Length - 1, ref minValue, ref maxValue, this.ScaleInvisible); if (minValue == maxValue || minValue == float.MaxValue || float.IsNaN(minValue) || float.IsInfinity(minValue) || maxValue == float.MinValue || float.IsNaN(maxValue) || float.IsInfinity(maxValue)) { this.Deactivate("Input data is corrupted and cannot be displayed...", false); return false; } if (this.IsLogScale && minValue > 0) { minValue -= (maxValue - minValue) * 0.025f; } else { minValue -= (maxValue - minValue) * 0.05f; } maxValue += (maxValue - minValue) * 0.05f; float tmpMinValue, tmpMaxValue; if (this.IsLogScale) { tmpMinValue = minValue < 0 ? (float)-Math.Log10(-minValue + 1) : (float)Math.Log10(minValue + 1); tmpMaxValue = maxValue < 0 ? (float)-Math.Log10(-maxValue + 1) : (float)Math.Log10(maxValue + 1); } else { tmpMinValue = minValue; tmpMaxValue = maxValue; } float coefX = (this.GraphRectangle.Width * 0.94f) / (dateSerie.Length - 1); float coefY = this.GraphRectangle.Height / (tmpMaxValue - tmpMinValue); matrixValueToScreen = new System.Drawing.Drawing2D.Matrix(); matrixValueToScreen.Translate(this.GraphRectangle.X + 20, tmpMaxValue * coefY + this.GraphRectangle.Y); matrixValueToScreen.Scale(coefX, -coefY); matrixScreenToValue = (System.Drawing.Drawing2D.Matrix)matrixValueToScreen.Clone(); matrixScreenToValue.Invert(); } else { this.Deactivate("App too small...", false); return false; } return true; } }
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()); } }
public void WriteGradientColorDefs(GradientFill[] gfs) { if (gfs.Length == 0) { return; } int count = gfs.Length; int totalBytes = 4; for (int i = 0; i < gfs.Length; i++) { int samples = gfs[i].Fills.Count; totalBytes += (samples * 4) + (samples * 1); // rgba ratio totalBytes += 1 + 6 * 2; // header and matrix } byte[] bytes = new byte[totalBytes]; // id8, count16 bytes[0] = (byte)DVex.GradientDefs; bytes[1] = 0; bytes[2] = (byte)((count & 0xFF00) >> 8); bytes[3] = (byte)(count & 0xFF); int index = 4; for (int i = 0; i < gfs.Length; i++) { int fillType = 0x00; // linearFill if (gfs[i].FillType == FillType.Radial) { fillType = 0x10; } int colorCount = gfs[i].Fills.Count; if (colorCount > 8) { colorCount = 8; Console.WriteLine("*Flash only supports 8 colors max in gradients"); } bytes[index++] = (byte)(fillType | colorCount); // add rgba+ratio array List <Color> colors = gfs[i].Fills; List <float> positions = gfs[i].Stops; // flash and gdi store colors & pos in opposite order for radials if (gfs[i].FillType == FillType.Radial) { int len = colors.Count; List <Color> tempc = new List <Color>(len); List <float> tempp = new List <float>(len); for (int col = 0; col < len; col++) { tempc[col] = colors[len - col - 1]; tempp[col] = 255 - positions[len - col - 1]; } colors = tempc; positions = tempp; } for (int j = 0; j < colorCount; j++) { bytes[index++] = colors[j].R; bytes[index++] = colors[j].G; bytes[index++] = colors[j].B; int a = (int)(Math.Floor(colors[j].A / 2.55)); if (a >= 98) { a = 100; } if (a <= 2) { a = 0; } bytes[index++] = (byte)a; bytes[index++] = (byte)(((int)(positions[j] * 255)) & 0xFF); } // add matrix System.Drawing.Drawing2D.Matrix clone = gfs[i].Transform.GetDrawing2DMatrix(); clone.Scale(GradientFill.GradientVexRect.Size.Width, GradientFill.GradientVexRect.Size.Height); float[] mx = clone.Elements; clone.Dispose(); // add elements bytes[index++] = (byte)((((int)mx[0]) & 0xFF00) >> 8); bytes[index++] = (byte)(((int)mx[0]) & 0xFF); bytes[index++] = (byte)((((int)mx[1]) & 0xFF00) >> 8); bytes[index++] = (byte)(((int)mx[1]) & 0xFF); bytes[index++] = (byte)((((int)mx[2]) & 0xFF00) >> 8); bytes[index++] = (byte)(((int)mx[2]) & 0xFF); bytes[index++] = (byte)((((int)mx[3]) & 0xFF00) >> 8); bytes[index++] = (byte)(((int)mx[3]) & 0xFF); bytes[index++] = (byte)((((int)mx[4]) & 0xFF00) >> 8); bytes[index++] = (byte)(((int)mx[4]) & 0xFF); bytes[index++] = (byte)((((int)mx[5]) & 0xFF00) >> 8); bytes[index++] = (byte)(((int)mx[5]) & 0xFF); FillDefs.Add(gfs[i]); } WriteByteArray(bytes); }
private void GraphicsView_Paint(object sender, PaintEventArgs e) { #if DEBUG if (this.DesignMode) return; #endif Graphics gr = e.Graphics; gr.Clear(Color.White); // if (HighPrecisionDraw) { gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; gr.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; } // gr.DrawString(string.Format("ZoomScale: {0}", Scale), Font, Brushes.Black, 0, 0); System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix(); m.Scale(ZoomScale, ZoomScale, System.Drawing.Drawing2D.MatrixOrder.Append); m.Translate(Translate.X, Translate.Y, System.Drawing.Drawing2D.MatrixOrder.Append); gr.Transform = m; cgmimage.Draw(gr); }
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; } }
protected override void OnPaint(PaintEventArgs e) { Graphics grfx = e.Graphics; SolidBrush HintergrundBrush = new SolidBrush(_Hintergrundfarbe); SolidBrush ControlHintergrundBrush = new SolidBrush(this.BackColor); Pen Stift1 = new Pen(_FarbeStift1, 0F); Pen Stift2 = new Pen(_FarbeStift2, 0F); Pen Stift3 = new Pen(_FarbeStift3, 0F); Pen Stift4 = new Pen(_FarbeStift4, 0F); Pen Stift5 = new Pen(_FarbeStift5, 0F); Pen Stift6 = new Pen(_FarbeStift6, 0F); Pen Stift7 = new Pen(_FarbeStift7, 0F); Pen Stift8 = new Pen(_FarbeStift8, 0F); Pen ZeichenStift = Stift1; System.Drawing.Drawing2D.Matrix ZeichenMatrix = null; float Skalierung = 0F; grfx.SmoothingMode = _ZeichenQualität; grfx.FillRectangle(ControlHintergrundBrush, this.ClientRectangle); ZeichenMatrix = new System.Drawing.Drawing2D.Matrix(); if (_AnsichtSkalieren) { Skalierung = (float)Math.Min( ((float)this.Width - 6F) / (_HPGL.MaximaleXKoordinate - _HPGL.MinimaleXKoordinate), ((float)this.Height - 6F) / (_HPGL.MaximaleYKoordinate - _HPGL.MinimaleYKoordinate) ); ZeichenMatrix.Translate( (((float)_HPGL.MinimaleXKoordinate * Skalierung * -1F) + 3F), ((float)this.Height - 3F) + ((float)_HPGL.MinimaleYKoordinate * Skalierung) ); } else { Skalierung = Math.Min( ((float)this.Width - 6F) / (PlotterMaxX - PlotterMinX), ((float)this.Height - 6F) / (PlotterMaxY - PlotterMinY) ); ZeichenMatrix.Translate(3, this.Height - 3); } ZeichenMatrix.Scale(Skalierung, -Skalierung); grfx.Transform = ZeichenMatrix; grfx.FillRectangle(HintergrundBrush, PlotterMinX, PlotterMinY, PlotterMaxX, PlotterMaxY); grfx.DrawRectangle(Stift1, PlotterMinX, PlotterMinY, PlotterMaxX, PlotterMaxY); if (_Linien != null) { foreach (HPGLElemente.Linie ZeichenLinie in _Linien) { switch (ZeichenLinie.Pen) { case 1: ZeichenStift = Stift1; break; case 2: ZeichenStift = Stift2; break; case 3: ZeichenStift = Stift3; break; case 4: ZeichenStift = Stift4; break; case 5: ZeichenStift = Stift5; break; case 6: ZeichenStift = Stift6; break; case 7: ZeichenStift = Stift7; break; case 8: ZeichenStift = Stift8; break; } grfx.DrawLine( ZeichenStift, (float)ZeichenLinie.StartX, (float)ZeichenLinie.StartY, (float)ZeichenLinie.EndX, (float)ZeichenLinie.EndY ); } } }
/// <summary> ///获取低压台区网络图 /// </summary> /// <param name="tqcode"></param> /// <returns></returns> public static Bitmap GetDytqMap(string tqcode ,int width,int height) { int w = width; int h = height; Bitmap bp = new Bitmap(w, h); Graphics g = Graphics.FromImage(bp); IList<PS_xl> list = Ebada.Client.ClientHelper.PlatformSqlMap.GetList<PS_xl>("where linecode like '" + tqcode + "%' and linevol='0.4'"); RectangleF rf = RectangleF.Empty; int bl = 10000; Dictionary<PS_xl, IList<PS_gt>> gts = new Dictionary<PS_xl, IList<PS_gt>>(); List<PS_gtsb> gtsbs = new List<PS_gtsb>(); foreach (PS_xl xl in list) { IList<PS_gt> gtlist = Client.ClientHelper.PlatformSqlMap.GetList<PS_gt>("where linecode ='" + xl.LineCode + "' order by gtcode"); if (gtlist.Count == 0) continue; IList<PS_gtsb> gtsblist = Client.ClientHelper.PlatformSqlMap.GetList<PS_gtsb>(" where sbtype like '17%' and gtid in (select gtid from ps_gt where linecode ='" + xl.LineCode + "')"); gtsbs.AddRange(gtsblist); IList<PS_gt> gtlist2 = new List<PS_gt>(); foreach (PS_gt gt in gtlist) { if (gt.gtLat == 0 || gt.gtLon == 0) continue; gtlist2.Add(gt); if (rf.IsEmpty) rf = new RectangleF((float)gt.gtLon*bl, (float)gt.gtLat*bl, 1f, 1f); else rf=RectangleF.Union(rf,new RectangleF((float)gt.gtLon*bl, (float)gt.gtLat*bl,1f,1f)); //rf..Inflate((float)gt.gtLon, (float)gt.gtLat); } gts.Add(xl, gtlist2); } DataTable gtbhtable = Ebada.Core.ConvertHelper.ToDataTable(gtsbs,typeof(PS_gtsb)); //g.TranslateTransform(-rf.X, -rf.Y); rf.Inflate(3, 3); System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix(); matrix.Translate(-rf.X, -rf.Y); float f1=w / rf.Width; float f2=h/rf.Height; float scale = Math.Min(f1,f2); matrix.Scale(scale, scale, System.Drawing.Drawing2D.MatrixOrder.Append); if (f1 < f2) matrix.Translate(0, (h - f1 * rf.Height) / 2, System.Drawing.Drawing2D.MatrixOrder.Append); else matrix.Translate((w - f2 * rf.Width) / 2, 0, System.Drawing.Drawing2D.MatrixOrder.Append); List<PointF> plist = new List<PointF>(); g.Clear(Color.White); g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; Font f = new Font("宋体", 9); PointF p0 = Point.Empty; Pen pen0 = new Pen(Color.Blue); pen0.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash; List<string> gt0list = new List<string>();//记录重叠杆塔 List<RectangleF> gtboxlist = new List<RectangleF>(); foreach (PS_xl xl in gts.Keys) { plist.Clear(); foreach (PS_gt gt in gts[xl]) { plist.Add(new PointF((float)gt.gtLon*bl, (float)gt.gtLat*bl)); } if (plist.Count <2) continue; PointF[] pts=plist.ToArray(); matrix.TransformPoints(pts); for(int i=0;i<pts.Length;i++){ pts[i].Y = h - pts[i].Y; } g.DrawLines(Pens.Blue,pts ); bool b1 = Math.Abs(pts[0].X - pts[1].X) > Math.Abs(pts[0].Y - pts[1].Y); Point offset = new Point(b1 ? 0 : 20, b1 ? 20 : 0); int gtnum = 0; for(int i=0;i<pts.Length;i++) { PS_gt gt =gts[xl][i]; if (gt.gtLat==0.0m||gt.gtLon==0.0m) continue; if (gt.gtJg == "是" && i==0) { if (xl.ParentID.Length > 10) continue;//台区下干线除外 PointF pf0 = pts[i]; bool ret = false; if (gt0list.Contains(xl.ParentID)) { foreach (RectangleF rtf in gtboxlist) { if (rtf.Contains(pf0)) { ret = true; break; } } } else { gt0list.Add(xl.ParentID); } if (ret) continue; RectangleF rtf0 = RectangleF.Empty; rtf0.Location = pf0; rtf0.Inflate(10, 10); gtboxlist.Add(rtf0); } DataRow[] rows= gtbhtable.Select("gtid='" + gt.gtID + "'"); int n = 1; foreach (DataRow row in rows) { PS_gtsb gtsb = Ebada.Core.ConvertHelper.RowToObject<PS_gtsb>(row); n *= -1; PointF pf = new PointF(pts[i].X + (n * offset.X), pts[i].Y + (n * offset.Y)); RectangleF rtf = Rectangle.Empty; rtf.Location = pf; rtf.Inflate(12, 5); Rectangle rt =Rectangle.Round(rtf); g.DrawLine(Pens.Red, pts[i], pf); g.FillRectangle(Brushes.White, rt); g.DrawRectangle(Pens.Red, rt); string num= gtsb.sbModle.Substring(0,1); if (gtsb.sbNumber > 1) num = num + "x" + gtsb.sbNumber; StringFormat sf =new StringFormat(); sf.Alignment= StringAlignment.Center; //sf.LineAlignment= StringAlignment.Center; g.DrawString(num, f, Brushes.Red, rtf,sf); if (n == 1) break; } g.FillEllipse(Brushes.White, pts[i].X - 5, pts[i].Y - 5, 10, 10); if (gt.gtJg == "是") { g.DrawEllipse(pen0, pts[i].X - 5, pts[i].Y - 5, 10, 10); } else { gtnum += 1; g.DrawEllipse(Pens.Blue, pts[i].X - 5, pts[i].Y - 5, 10, 10); g.DrawString((int)gt.gtHeight + "/" + (gtnum), f, Brushes.Black, pts[i].X - 10, pts[i].Y + 5); } } p0 = Point.Empty; } Hashtable ht_linenum = new Hashtable(); ht_linenum.Add("一线", "1"); ht_linenum.Add("二线", "2"); ht_linenum.Add("三线", "3"); ht_linenum.Add("四线", "4"); foreach (PS_xl xl in gts.Keys) { plist.Clear(); foreach (PS_gt gt in gts[xl]) { plist.Add(new PointF((float)gt.gtLon * bl, (float)gt.gtLat * bl)); } if (plist.Count < 2) continue; PointF[] pts = plist.ToArray(); matrix.TransformPoints(pts); for (int i = 0; i < pts.Length; i++) { pts[i].Y = h - pts[i].Y; } PointF curgt = pts[0]; for (int i = 1; i < pts.Length; i++) { PS_gt gt = gts[xl][i]; if (gt.gtSpan > 1) { drawSpan(g,(int)gt.gtSpan, curgt.X, curgt.Y, pts[i].X, pts[i].Y); } curgt = pts[i]; } object obj = ht_linenum[xl.lineNum] ?? "2"; string linenum = "X" + obj.ToString(); drawLineModel(g, xl.WireType+linenum, pts[pts.Length - 2].X, pts[pts.Length -2].Y, pts[pts.Length - 1].X, pts[pts.Length - 1].Y); } //绘制10线路方向 IList<PS_xl> xllist0 = Client.ClientHelper.PlatformSqlMap.GetList<PS_xl>("where parentid='" + tqcode + "' and linevol ='0.4' "); foreach (PS_xl xl0 in xllist0) { IList<PS_gt> gtlist = Client.ClientHelper.PlatformSqlMap.GetList<PS_gt>("where linecode='" + xl0.LineCode + "' order by gtcode"); if (gtlist.Count >= 2) { PointF p1 = new PointF((float)gtlist[0].gtLon * bl, (float)gtlist[0].gtLat * bl); PointF p2 = new PointF((float)gtlist[1].gtLon * bl, (float)gtlist[1].gtLat * bl); PointF[] pts = new PointF[] { p1, p2 }; matrix.TransformPoints(pts); //drawArrow(g, pts[0].X, h - pts[0].Y, pts[1].X, h - pts[1].Y); } } PS_tq tq = Client.ClientHelper.PlatformSqlMap.GetOne<PS_tq>("where tqcode='" + tqcode + "'"); if (tq != null) { IList<PS_gt> gtlist = Client.ClientHelper.PlatformSqlMap.GetList<PS_gt>("where linecode='" + tq.xlCode2 + "' order by gtcode"); if (gtlist.Count>1) { for(int i=0;i<gtlist.Count;i++) { if (gtlist[i].gtCode == tq.gtID) { if (i > 0) { PointF p1 = new PointF((float)gtlist[i-1].gtLon * bl, (float)gtlist[i-1].gtLat * bl); PointF p2 = new PointF((float)gtlist[i].gtLon * bl, (float)gtlist[i].gtLat * bl); PointF[] pts = new PointF[] { p1, p2 }; matrix.TransformPoints(pts); drawArrow(g, pts[0].X, h - pts[0].Y, pts[1].X, h - pts[1].Y); } break; } } } } //绘制指南针 g.TranslateTransform(width - 50, 20); g.ScaleTransform(1.5f, 1.5f); draw指南针(g); return bp; }
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); }
/// <summary> /// When the element is called on to be painted this method is called /// </summary> /// <param name="e"></param> protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Bitmap tempBuffer = new Bitmap(Width, Height); Graphics tempGraph = Graphics.FromImage(tempBuffer); tempGraph.SmoothingMode = _drawingQuality; Rectangle inflatedInvalidationRect = Rectangle.Inflate(e.ClipRectangle,5,5); if (IsInitialized) { tempGraph.DrawImage(_backBuffer, inflatedInvalidationRect, inflatedInvalidationRect, GraphicsUnit.Pixel); } else { UpdateBackBuffer(); tempGraph.DrawImage(_backBuffer, new Point(0, 0)); } //Draws selected shapes last if (_modelElementsSelected.Count > 0) { for (int i = _modelElementsSelected.Count - 1; i >= 0; i--) { ModelElement me = _modelElementsSelected[i]; System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix(); Point translator = VirtualToPixel(me.Location.X,me.Location.Y); m.Translate(translator.X, translator.Y); m.Scale(_virtualZoom, _virtualZoom); tempGraph.Transform = m; me.Paint(tempGraph); tempGraph.Transform = new System.Drawing.Drawing2D.Matrix(); } } //If the users is dragging a select box we draw it here if (_selectBoxDraw) { SolidBrush highlightBrush = new SolidBrush(Color.FromArgb(30,SystemColors.Highlight)); tempGraph.FillRectangle(highlightBrush, Rectangle.Inflate(_selectBox,-1,-1)); Rectangle outlineRect = new Rectangle(_selectBox.X, _selectBox.Y, _selectBox.Width - 1, _selectBox.Height - 1); tempGraph.DrawRectangle(SystemPens.Highlight, outlineRect); //garbage collection highlightBrush.Dispose(); } //Draws the temporary bitmap to the screen e.Graphics.SmoothingMode = _drawingQuality; e.Graphics.DrawImage(tempBuffer, inflatedInvalidationRect, inflatedInvalidationRect, GraphicsUnit.Pixel); //Garbage collection tempBuffer.Dispose(); tempGraph.Dispose(); }
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 GraphicsView_MouseMove(object sender, MouseEventArgs e) { if (movestart == null) return; if (!TranslateFocus) return; System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix(); //m.Translate(Translate.X, Translate.Y, System.Drawing.Drawing2D.MatrixOrder.Append); m.Scale(ZoomScale, ZoomScale, System.Drawing.Drawing2D.MatrixOrder.Append); m.Invert(); Point movement = new Point(movestart.X - e.X, movestart.Y - e.Y); movement.X = -movement.X; movement.Y = -movement.Y; Point[] t = new Point[] { movement }; m.TransformPoints(t); movement = t[0]; Translate.X -= movestart.X - e.X; Translate.Y -= movestart.Y - e.Y; movestart = e.Location; HighPrecisionDraw = false; this.Refresh(); }