protected virtual void ModifyCurrentMousePrintAreaCoordinate() { if (_currentPoint > 0) { bool bControlKey = Keyboard.Modifiers.HasFlag(ModifierKeys.Control); // Control pressed bool bShiftKey = Keyboard.Modifiers.HasFlag(ModifierKeys.Shift); // draw a temporary lines of all points to the current mouse position if (bShiftKey && _currentPoint > 0) { double x = _positionCurrentMouseInRootLayerCoordinates.X - _Points[_currentPoint - 1].RootLayerCoordinates.X; double y = _positionCurrentMouseInRootLayerCoordinates.Y - _Points[_currentPoint - 1].RootLayerCoordinates.Y; double r = Math.Sqrt(x * x + y * y); double d = Math.Atan2(y, x); d = Math.Floor(0.5 + 12 * d / Math.PI); // lock every 15 degrees d = d * Math.PI / 12; x = r * Math.Cos(d); y = r * Math.Sin(d); _positionCurrentMouseInRootLayerCoordinates = new PointD2D( (x + _Points[_currentPoint - 1].RootLayerCoordinates.X), (y + _Points[_currentPoint - 1].RootLayerCoordinates.Y) ); } } }
public TextGraphic(PointD2D graphicPosition, string text, FontX textFont, NamedColor textColor, double Rotation) : this(graphicPosition, text, textFont, textColor) { this.Rotation = Rotation; }
public override void UpdateAreaSize(PointD2D size) { base.UpdateAreaSize(size); _midX = _layerWidth / 2; _midY = _layerHeight / 2; _radius = Math.Min(_midX, _midY); }
public virtual void SetRelativeSizePositionFromAbsoluteValues(PointD2D absSize, PointD2D absPos) { var oldSizeX = SizeX; var oldSizeY = SizeY; var oldPosX = PositionX; var oldPosY = PositionY; if (_parentSize.X == 0) { throw new InvalidOperationException("ParentSize.X is zero. This would lead to an undefined relative value!"); } if (_parentSize.Y == 0) { throw new InvalidOperationException("ParentSize.Y is zero. This would lead to an undefined relative value!"); } InternalSetSizeSilent( RADouble.NewRel(absSize.X / _parentSize.X), RADouble.NewRel(absSize.Y / _parentSize.Y) ); _positionX = RADouble.NewRel(absPos.X / _parentSize.X); _positionY = RADouble.NewRel(absPos.Y / _parentSize.Y); if (oldSizeX != _sizeX || oldSizeY != _sizeY || oldPosX != _positionX || oldPosY != _positionY) { EhSelfChanged(); } }
public EmbeddedImageGraphic(PointD2D graphicPosition, ImageProxy startingImage) : this() { SetPosition(graphicPosition, Main.EventFiring.Suppressed); Image = startingImage; }
/// <summary>Initializes a new instance of the <see cref="GraphViewLayout"/> class.</summary> /// <param name="isAutoZoomActive">If set to <c>true</c> auto zoom is active.</param> /// <param name="zoomFactor">The zoom factor.</param> /// <param name="graphDocument">The graph document.</param> /// <param name="viewPortsUpperLeftInRootLayerCoord">Vector from the upper left corner of the graph to the upper left corner of the view port.</param> public GraphViewLayout(bool isAutoZoomActive, double zoomFactor, GraphDocument graphDocument, PointD2D viewPortsUpperLeftInRootLayerCoord) { _isAutoZoomActive = isAutoZoomActive; _zoomFactor = zoomFactor; _positionOfViewportsUpperLeftCornerInRootLayerCoordinates = viewPortsUpperLeftInRootLayerCoord; _graphDocument = graphDocument; }
/// <summary> /// Handles the mouse up event. /// </summary> /// <param name="position">Mouse position.</param> /// <param name="e">MouseEventArgs as provided by the view.</param> /// <returns>The next mouse state handler that should handle mouse events.</returns> public override void OnMouseUp(PointD2D position, MouseButtonEventArgs e) { base.OnMouseUp(position, e); if (e.LeftButton == MouseButtonState.Released && null != _rectangleSelectionArea_GraphCoordinates) { _grac.FindGraphObjectInRootLayerRectangle(_rectangleSelectionArea_GraphCoordinates.Value, out var foundObjects); AddSelectedObjectsFromRectangularSelection(foundObjects); (_grac.ViewObject as IGraphView).ReleaseCaptureMouseOnCanvas(); _rectangleSelectionArea_GraphCoordinates = null; _grac.RenderOverlay(); } else if (ActiveGrip != null) { bool bRefresh = _wereObjectsMoved; // repaint the graph when objects were really moved bool bRepaint = false; _wereObjectsMoved = false; _grac.Doc.Resume(ref _graphDocumentChangedSuppressor); bool chooseNextLevel = ActiveGrip.Deactivate(); ActiveGrip = null; if (chooseNextLevel && null != SingleSelectedHitTestObject) { DisplayedGripLevel = SingleSelectedHitTestObject.GetNextGripLevel(DisplayedGripLevel); bRepaint = true; } _grac.RenderOverlay(); } }
public LinkedImageGraphic(PointD2D graphicPosition, string ImagePath) : this() { SetPosition(graphicPosition, Main.EventFiring.Suppressed); this.ImagePath = ImagePath; }
/// <summary> /// Returns the index of a scatter point that is nearest to the location <c>hitpoint</c> /// </summary> /// <param name="layer">The layer in which this plot item is drawn into.</param> /// <param name="hitpoint">The point where the mouse is pressed.</param> /// <returns>The information about the point that is nearest to the location, or null if it can not be determined.</returns> public XYScatterPointInformation GetNearestPlotPoint(IPlotArea layer, PointD2D hitpoint) { Processed2DPlotData pdata; if (null != (pdata = _cachedPlotDataUsedForPainting)) { PlotRangeList rangeList = pdata.RangeList; PointF[] ptArray = pdata.PlotPointsInAbsoluteLayerCoordinates; double mindistance = double.MaxValue; int minindex = -1; for (int i = 1; i < ptArray.Length; i++) { double distance = Math2D.SquareDistanceLineToPoint(hitpoint, ptArray[i - 1], ptArray[i]); if (distance < mindistance) { mindistance = distance; minindex = Math2D.Distance(ptArray[i - 1], hitpoint) < Math2D.Distance(ptArray[i], hitpoint) ? i - 1 : i; } } // ok, minindex is the point we are looking for // so we have a look in the rangeList, what row it belongs to int rowindex = rangeList.GetRowIndexForPlotIndex(minindex); return(new XYScatterPointInformation(ptArray[minindex], rowindex, minindex)); } return(null); }
private void OnGraphPanel_SizeChanged(PointD2D newSize) { if (!(newSize.X > 0 && newSize.Y > 0)) { return; } _guiCanvas.Clip = new RectangleGeometry(new Rect(0, 0, newSize.X, newSize.Y)); if (null == _graphImage.Source) { // invalidate the cached graph sizes in order to force a new rendering _cachedGraphSize_Pixels = new System.Drawing.Size(0, 0); _cachedGraphSize_96thInch = new PointD2D(0, 0); } if (newSize != _cachedGraphSize_96thInch) { _cachedGraphSize_96thInch = newSize; var screenResolution = Current.Gui.ScreenResolutionDpi; var graphSizePixels = screenResolution * _cachedGraphSize_96thInch / 96.0; _cachedGraphSize_Pixels = new System.Drawing.Size((int)graphSizePixels.X, (int)graphSizePixels.Y); Controller?.EhView_GraphPanelSizeChanged(); // inform controller ShowCachedGraphImage(); _isGraphUpToDate = false; if (_isGraphVisible) { ((IGraphView)this).InvalidateCachedGraphBitmapAndRepaint(); } } }
/// <summary> /// Handles the drawing of a straight single line. /// </summary> /// <param name="position">Mouse position.</param> /// <param name="e">EventArgs.</param> /// <returns>The mouse state handler for handling the next mouse events.</returns> public override void OnClick(PointD2D position, MouseButtonEventArgs e) { base.OnClick(position, e); if (0 == _currentPoint) { _cachedActiveLayer = _grac.ActiveLayer; _cachedActiveLayerTransformation = _cachedActiveLayer.TransformationFromRootToHere(); _cachedActiveLayerTransformationGdi = _cachedActiveLayerTransformation; } // get the page coordinates (in Point (1/72") units) var rootLayerCoord = _positionCurrentMouseInRootLayerCoordinates; // with knowledge of the current active layer, calculate the layer coordinates from them var layerCoord = _cachedActiveLayerTransformation.InverseTransformPoint(rootLayerCoord); _Points[_currentPoint].LayerCoordinates = layerCoord; _Points[_currentPoint].RootLayerCoordinates = rootLayerCoord; _currentPoint++; if (2 == _currentPoint) { FinishDrawing(); _currentPoint = 0; _grac.SetGraphToolFromInternal(NextMouseHandlerType); } }
public override bool InitializeDocument(params object[] args) { if (args.Length < 2) { return(false); } if (!(args[0] is GridPartitioning)) { return(false); } if (args[1] is PointD2D) { _parentLayerSize = (PointD2D)args[1]; } else if (args[1] is HostLayer) { _parentLayerSize = ((HostLayer)args[1]).Size; } else { _parentLayerSize = new PointD2D(600, 400); } return(base.InitializeDocument(args)); }
/// <summary> /// Handles the mouse doubleclick event. /// </summary> /// <param name="position">Mouse position.</param> /// <param name="e">EventArgs as provided by the view.</param> /// <returns>The next mouse state handler that should handle mouse events.</returns> public override void OnDoubleClick(PointD2D position, MouseButtonEventArgs e) { base.OnDoubleClick(position, e); // if there is exactly one object selected, try to open the corresponding configuration dialog if (_selectedObjects.Count == 1) { IEnumerator graphEnum = _selectedObjects.GetEnumerator(); // get the enumerator graphEnum.MoveNext(); // set the enumerator to the first item var graphObject = (IHitTestObject)graphEnum.Current; // Set the currently active layer to the layer the clicked object is belonging to. if (graphObject.ParentLayer != null && !object.ReferenceEquals(_grac.ActiveLayer, graphObject.ParentLayer)) { _grac.EhView_CurrentLayerChoosen(graphObject.ParentLayer.IndexOf().ToArray(), false); // Sets the current active layer } if (graphObject.DoubleClick != null) { //EndMovingObjects(); // this will resume the suspended graph so that pressing the "Apply" button in a dialog will result in a visible change ClearSelections(); // this will resume the suspended graph so that pressing the "Apply" button in a dialog will result in a visible change graphObject.OnDoubleClick(); //ClearSelections(); } } }
/// <summary> /// Activates this grip, providing the initial position of the mouse. /// </summary> /// <param name="initialPosition">Initial position of the mouse.</param> /// <param name="isActivatedUponCreation">If true the activation is called right after creation of this handle. If false, /// thie activation is due to a regular mouse click in this grip.</param> public void Activate(PointD2D initialPosition, bool isActivatedUponCreation) { foreach (var ele in GripList) { ele.Activate(initialPosition, isActivatedUponCreation); } }
protected override void Initialize(bool initData) { base.Initialize(initData); if (initData) { _srcSize = _doc.GetImageSizePt(); _docScale = new PointD2D(_doc.Size.X / _srcSize.X, _doc.Size.Y / _srcSize.Y); _docLocation = new ItemLocationDirect(); _docLocation.CopyFrom(_doc.Location); _docLocation.Scale = new PointD2D(_doc.Size.X / _srcSize.X, _doc.Size.Y / _srcSize.Y); _locationController = new ItemLocationDirectController() { UseDocumentCopy = UseDocument.Directly }; _locationController.InitializeDocument(new object[] { _docLocation }); Current.Gui.FindAndAttachControlTo(_locationController); _locationController.SizeXChanged += EhLocController_SizeXChanged; _locationController.SizeYChanged += EhLocController_SizeYChanged; _locationController.ScaleXChanged += EhLocController_ScaleXChanged; _locationController.ScaleYChanged += EhLocController_ScaleYChanged; _locationController.ShowSizeElements(true, !_doc.IsSizeCalculationBasedOnSourceSize); _locationController.ShowScaleElements(true, _doc.IsSizeCalculationBasedOnSourceSize); } if (_view != null) { _view.SourceSize = _srcSize; _view.AspectPreserving = _doc.AspectRatioPreserving; _view.IsSizeCalculationBasedOnSourceSize = _doc.IsSizeCalculationBasedOnSourceSize; _view.LocationView = _locationController.ViewObject; } }
public override void ChangeSize(double?x, double?y) { var hit = _hitobject as GraphicBase; PointD2D currentSizeRootCoord = ObjectOutlineForArrangements.GetBounds().Size; PointD2D destinationSizeRootCoord = currentSizeRootCoord; if (x.HasValue) { destinationSizeRootCoord = destinationSizeRootCoord.WithX(x.Value); } if (y.HasValue) { destinationSizeRootCoord = destinationSizeRootCoord.WithY(y.Value); } if (null != hit) { if (!hit.AutoSize) { var t = _matrix.Clone(); t.AppendTransform(hit._transformation); var innerRect = RectangleD2DExtensions.GetIncludedTransformedRectangle(new RectangleD2D(PointD2D.Empty, destinationSizeRootCoord), t.SX, t.RX, t.RY, t.SY); hit.Width = innerRect.Width; hit.Height = innerRect.Height; } } }
private void OnGraphPanel_SizeChanged(PointD2D newSize) { if (!(newSize.X > 0 && newSize.Y > 0)) { return; } if (null == _renderer) { _d3dCanvas.Source = new D3D10ImageSource(Controller?.Doc?.Name); _renderer = new D3D10RendererToImageSource(_scene, (D3D10ImageSource)_d3dCanvas.Source, Controller?.Doc?.Name); // invalidate the cached graph sizes in order to force a new rendering _cachedGraphSize_Pixels = new System.Drawing.Size(0, 0); _cachedGraphSize_96thInch = new PointD2D(0, 0); } if (newSize != _cachedGraphSize_96thInch) { _cachedGraphSize_96thInch = newSize; var screenResolution = Current.Gui.ScreenResolutionDpi; var graphSizePixels = screenResolution * _cachedGraphSize_96thInch / 96.0; _cachedGraphSize_Pixels = new System.Drawing.Size((int)graphSizePixels.X, (int)graphSizePixels.Y); _renderer.SetRenderSize(_cachedGraphSize_Pixels.Width, _cachedGraphSize_Pixels.Height); Controller?.EhView_GraphPanelSizeChanged(); // inform controller } }
public override System.Drawing.Image GetImage() { if (_image != null && _image.IsAlive) { return((System.Drawing.Image)_image.Target); } System.Drawing.Image image = null; if (_url != null) { image = Current.ResourceService.GetBitmap(_url); } if (null != image) { _imageSizePt = new PointD2D(image.Width * 72.0 / image.HorizontalResolution, image.Height * 72.0 / image.VerticalResolution); _image = new WeakReference(image); } else { _imageSizePt = PointD2D.Empty; _image = null; } return(image); }
/// <summary> /// Sets the selected pivot values for X and Y. Additionally, the reference size is required. /// </summary> /// <param name="pivotX">The pivot x value.</param> /// <param name="pivotY">The pivot y value.</param> /// <param name="referenceSize">Size of the reference area.</param> public void SetSelectedPivot(RADouble pivotX, RADouble pivotY, PointD2D referenceSize) { _pivotX = pivotX; _pivotY = pivotY; _percentLayerXSizeUnit.ReferenceQuantity = new DimensionfulQuantity(referenceSize.X, AUL.Point.Instance); _percentLayerYSizeUnit.ReferenceQuantity = new DimensionfulQuantity(referenceSize.Y, AUL.Point.Instance); _xSizeEnvironment = new QuantityWithUnitGuiEnvironment(GuiLengthUnits.Collection, _percentLayerXSizeUnit); _ySizeEnvironment = new QuantityWithUnitGuiEnvironment(GuiLengthUnits.Collection, _percentLayerYSizeUnit); _guiPivotX.UnitEnvironment = _xSizeEnvironment; _guiPivotY.UnitEnvironment = _ySizeEnvironment; _guiPivotX.SelectedQuantity = _pivotX.IsAbsolute ? new DimensionfulQuantity(_pivotX.Value, AUL.Point.Instance) : new DimensionfulQuantity(_pivotX.Value * 100, _percentLayerXSizeUnit); _guiPivotY.SelectedQuantity = _pivotY.IsAbsolute ? new DimensionfulQuantity(_pivotY.Value, AUL.Point.Instance) : new DimensionfulQuantity(_pivotY.Value * 100, _percentLayerYSizeUnit); if (CanUseRadioGridView()) { SetRadioButton(); SetUseOfRadioGrid(true); } else { SetUseOfRadioGrid(false); } SetVisibilityOfSwitchButton(); }
/// <summary> /// Modifies the current mouse root layer coordinates, so that Shift moves in 1% steps of the layer size, Ctrl in 5% steps, and Shift+Ctrl in 10% steps. /// </summary> protected virtual void ModifyCurrentMouseRootLayerCoordinates() { bool bControlKey = Keyboard.Modifiers.HasFlag(ModifierKeys.Control); // Control pressed bool bShiftKey = Keyboard.Modifiers.HasFlag(ModifierKeys.Shift); // draw a temporary lines of all points to the current mouse position int roundToParts = 0; if (bControlKey && bShiftKey) { roundToParts = 10; } else if (bControlKey) { roundToParts = 20; } else if (bShiftKey) { roundToParts = 100; } if (roundToParts > 0) { var layerCoord = _layerToEdit.TransformCoordinatesFromRootToHere(_positionCurrentMouseInRootLayerCoordinates); // Round the layer Coordinate to 1/100 of the size var layerCoordRounded = new PointD2D( _layerToEdit.Size.X * Math.Round(roundToParts * layerCoord.X / _layerToEdit.Size.X) / roundToParts, _layerToEdit.Size.Y * Math.Round(roundToParts * layerCoord.Y / _layerToEdit.Size.Y) / roundToParts); _positionCurrentMouseInRootLayerCoordinates = _layerToEdit.TransformCoordinatesFromHereToRoot(layerCoordRounded); } }
public void MoveGrip(PointD2D newPosition) { foreach (var ele in GripList) { ele.MoveGrip(newPosition); } }
/// <summary> /// Gets the grid line closest to our last mouse position. /// </summary> /// <param name="minDistanceSquared">The minimum distance (squared) between the closest grid line and our mouse position.</param> /// <param name="minIndex">The index of the closest grid line.</param> /// <param name="minInXGrid">If set to <c>true</c> the closest grid line is an x-grid line; otherwise it is an y-grid line.</param> private void GetClosestGridLine(out double minDistanceSquared, out int minIndex, out bool minInXGrid) { minDistanceSquared = double.PositiveInfinity; minIndex = 0; minInXGrid = true; for (int i = 0; i < _xGridLines.Length - 1; ++i) { var line = _xGridLines[i]; var dist = PointD2D.SquareDistanceLineToPoint(_positionCurrentMouseInRootLayerCoordinates, line.Org.RootLayerCoordinates, line.End.RootLayerCoordinates); if (minDistanceSquared > dist) { minDistanceSquared = dist; minIndex = i; minInXGrid = true; } } for (int i = 0; i < _yGridLines.Length - 1; ++i) { var line = _yGridLines[i]; var dist = PointD2D.SquareDistanceLineToPoint(_positionCurrentMouseInRootLayerCoordinates, line.Org.RootLayerCoordinates, line.End.RootLayerCoordinates); if (minDistanceSquared > dist) { minDistanceSquared = dist; minIndex = i; minInXGrid = false; } } }
protected virtual void InternalSetAbsoluteSizeSilent(PointD2D value) { RADouble sizeX, sizeY; if (_sizeX.IsAbsolute) { sizeX = RADouble.NewAbs(value.X); } else if (_parentSize.X != 0 && !double.IsNaN(_parentSize.X)) { sizeX = RADouble.NewRel(value.X / _parentSize.X); } else { throw new InvalidOperationException("_parentSize.X is undefined or zero"); } if (_sizeY.IsAbsolute) { sizeY = RADouble.NewAbs(value.Y); } else if (_parentSize.Y != 0 && !double.IsNaN(_parentSize.Y)) { sizeY = RADouble.NewRel(value.Y / _parentSize.Y); } else { throw new InvalidOperationException("_parentSize.Y is undefined or zero"); } InternalSetSizeSilent(sizeX, sizeY); }
/// <summary> /// Gets the circumference of a closed polygon. /// </summary> /// <param name="closedPolygon">The closed polygon.</param> /// <returns>The circumference of the given closed polygon.</returns> public static double GetClosedPolygonCircumference(IEnumerable <PointD2D> closedPolygon) { PointD2D firstPoint = default; PointD2D previous = default; double sum = 0.0; var numberOfPoints = 0; foreach (var pt in closedPolygon) { if (0 == numberOfPoints) { firstPoint = pt; } else { sum += Math.Sqrt((pt.X - previous.X) * (pt.X - previous.X) + (pt.Y - previous.Y) * (pt.Y - previous.Y)); } previous = pt; ++numberOfPoints; } if (numberOfPoints == 0) { throw new ArgumentException("Polygon is empty (has no point at all)", nameof(closedPolygon)); } else { var pt = firstPoint; sum += Math.Sqrt((pt.X - previous.X) * (pt.X - previous.X) + (pt.Y - previous.Y) * (pt.Y - previous.Y)); return(sum); } }
public static void Test_PolygonArea02_Nothing() { var testPoints = new PointD2D[0]; var area = Math2D.PolygonArea(testPoints); Assert.AreEqual(0, area); }
/// <summary> /// Gets a windows metafile placeable header that can be preprended to the metafile bytes (only for files on disk). /// This header contains information about the bounding box of the metafile. /// </summary> /// <param name="docSize">Size of the document in points (1/72 inch).</param> /// <returns>The windows metafile placeable header as byte array.</returns> public static byte[] GetWmfPlaceableHeaderBytes(PointD2D docSize) { var header = new WmfPlaceableFileHeader(); const ushort twips_per_inch = 1440; header.key = 0x9aC6CDD7; // magic number header.hmf = 0; header.bboxLeft = 0; header.bboxRight = (ushort)(twips_per_inch * docSize.X / 72); header.bboxTop = 0; header.bboxBottom = (ushort)(twips_per_inch * docSize.Y / 72); header.inch = twips_per_inch; header.reserved = 0; // Calculate checksum for first 10 WORDs. ushort checksum = 0; byte[] header_bytes = StructureToByteArray(header); for (int i = 0; i < 10; i++) { checksum ^= BitConverter.ToUInt16(header_bytes, i * 2); } header.checksum = checksum; // Construct the file in-memory. header_bytes = StructureToByteArray(header); return(header_bytes); }
private void DisplayCrossCoordinatesAndDifference(PointD2D rootLayerCoord) { if (_showRootLayerPrintCoordinates) { var crossLayerCoord = _cachedActiveLayerTransformation.InverseTransformPoint(_positionOfCrossInRootLayerCoordinates); var layerCoord = _cachedActiveLayerTransformation.InverseTransformPoint(rootLayerCoord); Current.DataDisplay.WriteTwoLines( string.Format("Layer({0}) XS={1} pt, YS={2} pt", _cachedActiveLayer.Name, crossLayerCoord.X, crossLayerCoord.Y), string.Format("DeltaXS={0} pt, DeltaYS={1} pt, Distance={2} pt", layerCoord.X - crossLayerCoord.X, layerCoord.Y - crossLayerCoord.Y, Calc.RMath.Hypot(layerCoord.X - crossLayerCoord.X, layerCoord.Y - crossLayerCoord.Y)) ); } else { if (CalculateCrossCoordinates(_positionOfCrossInRootLayerCoordinates, out var xphys, out var yphys) && CalculateCrossCoordinates(rootLayerCoord, out var xphys2, out var yphys2)) { double distance = double.NaN; AltaxoVariant dx = double.NaN, dy = double.NaN; try { dx = xphys2 - xphys; dy = yphys2 - yphys; var r2 = dx * dx + dy * dy; distance = Math.Sqrt(r2); } catch (Exception) { } Current.DataDisplay.WriteTwoLines( string.Format("Layer({0}) X={1}, Y={2}", _cachedActiveLayer.Name, xphys, yphys), string.Format("DeltaX={0}, DeltaY={1}, Distance={2}", dx, dy, distance) ); } } }
private void EhAspectRatioPreservingChanged() { _doc.AspectRatioPreserving = _view.AspectPreserving; _docScale = new PointD2D(_doc.Size.X / _srcSize.X, _doc.Size.Y / _srcSize.Y); //_view.DocScale = _docScale; //_view.DocSize = _doc.Size; }
/// <summary> /// Handles the drawing of a straight single line. /// </summary> /// <param name="position">Mouse position.</param> /// <param name="e">EventArgs.</param> /// <returns>The mouse state handler for handling the next mouse events.</returns> public override void OnClick(PointD2D position, MouseButtonEventArgs e) { base.OnClick(position, e); if (0 == _currentPoint) { _cachedActiveLayer = _grac.ActiveLayer; _cachedActiveLayerTransformation = _cachedActiveLayer.TransformationFromRootToHere(); _cachedActiveLayerTransformationGdi = _cachedActiveLayerTransformation; } // get the page coordinates (in Point (1/72") units) var rootLayerCoord = _positionCurrentMouseInRootLayerCoordinates; // with knowledge of the current active layer, calculate the layer coordinates from them var layerCoord = _cachedActiveLayerTransformation.InverseTransformPoint(rootLayerCoord); if (e.ChangedButton == MouseButton.Right) { FinishDrawing(); } else { _Points.Add(new POINT() { LayerCoordinates = layerCoord, RootLayerCoordinates = rootLayerCoord }); _currentPoint++; } }
public LineShape(PointD2D startPosition, PointD2D endPosition, Altaxo.Main.Properties.IReadOnlyPropertyBag context) : this(startPosition, context) { _location.SizeX = RADouble.NewAbs(endPosition.X - startPosition.X); _location.SizeY = RADouble.NewAbs(endPosition.Y - startPosition.Y); }
public GraphDocumentDataObject(GraphDocumentBase graphDocument, ProjectFileComObject fileComObject, ComManager comManager) : base(comManager) { ComDebug.ReportInfo("{0} constructor.", this.GetType().Name); _dataAdviseHolder = new ManagedDataAdviseHolder(); _graphDocumentName = graphDocument.Name; _graphDocumentSize = graphDocument.Size; _graphExportOptions = graphDocument.GetPropertyValue(ClipboardRenderingOptions.PropertyKeyClipboardRenderingOptions, () => new ClipboardRenderingOptions()).Clone(); var embeddedRenderingOptions = graphDocument.GetPropertyValue(EmbeddedObjectRenderingOptions.PropertyKeyEmbeddedObjectRenderingOptions, () => null); if (null != embeddedRenderingOptions) _graphExportOptions.CopyFrom(embeddedRenderingOptions); // merge embedded rendering options if ((_graphExportOptions.RenderEnhancedMetafile && _graphExportOptions.RenderEnhancedMetafileAsVectorFormat) || (_graphExportOptions.RenderDropFile && _graphExportOptions.DropFileImageFormat == System.Drawing.Imaging.ImageFormat.Emf) ) { if (graphDocument is Altaxo.Graph.Gdi.GraphDocument) _graphDocumentMetafileImage = GraphDocumentExportActions.RenderAsEnhancedMetafileVectorFormat((Altaxo.Graph.Gdi.GraphDocument)graphDocument, _graphExportOptions); } if (null == _graphDocumentMetafileImage || _graphExportOptions.RenderBitmap || _graphExportOptions.RenderWindowsMetafile || (_graphExportOptions.RenderEnhancedMetafile && !_graphExportOptions.RenderEnhancedMetafileAsVectorFormat) || _graphExportOptions.RenderDropFile) { if (graphDocument is Altaxo.Graph.Gdi.GraphDocument) _graphDocumentBitmapImage = GraphDocumentExportActions.RenderAsBitmap((Altaxo.Graph.Gdi.GraphDocument)graphDocument, _graphExportOptions.BackgroundBrush, System.Drawing.Imaging.PixelFormat.Format32bppArgb, _graphExportOptions.SourceDpiResolution, _graphExportOptions.SourceDpiResolution / _graphExportOptions.OutputScalingFactor); else if (graphDocument is Altaxo.Graph.Graph3D.GraphDocument) _graphDocumentBitmapImage = Altaxo.Graph.Graph3D.GraphDocumentExportActions.RenderAsBitmap((Altaxo.Graph.Graph3D.GraphDocument)graphDocument, _graphExportOptions.BackgroundBrush, System.Drawing.Imaging.PixelFormat.Format32bppArgb, _graphExportOptions.SourceDpiResolution, _graphExportOptions.SourceDpiResolution / _graphExportOptions.OutputScalingFactor); else throw new NotImplementedException(); } if (_graphExportOptions.RenderEmbeddedObject) { var miniProjectBuilder = new Altaxo.Graph.Procedures.MiniProjectBuilder(); _altaxoMiniProject = miniProjectBuilder.GetMiniProject(graphDocument, true); } else { _altaxoMiniProject = null; } }
public void TestPointContains() { Rectangle r1 = new Rectangle() { X = 0, Y = 0, Height = 10, Width = 10 }; PointD2D p1 = new PointD2D() { X = 5, Y = 5 }; Assert.IsTrue(r1.Contains(p1)); p1 = new PointD2D() { X = 0, Y = 0 }; Assert.IsTrue(r1.Contains(p1)); p1 = new PointD2D() { X = 9, Y = 9 }; Assert.IsTrue(r1.Contains(p1)); p1 = new PointD2D() { X = -1, Y = 0 }; Assert.IsFalse(r1.Contains(p1)); p1 = new PointD2D() { X = 10, Y = 0 }; Assert.IsFalse(r1.Contains(p1)); }
public TextGraphic(PointD2D graphicPosition, string text, FontX textFont, NamedColor textColor) : base(new ItemLocationDirectAutoSize()) { this.SetPosition(graphicPosition, Main.EventFiring.Suppressed); this.Font = textFont; this.Text = text; this.Color = textColor; }
public DensityLegendArea(PointD2D size, bool isXYInterchanged, bool isXReversed, Scale scale, TickSpacing tickSpacing) { _size = size; _scales = new ScaleCollection() { ParentObject = this }; _scales[0] = scale; scale.TickSpacing = tickSpacing; _scales[1] = new LinearScale() { TickSpacing = new NoTickSpacing() }; _coordinateSystem = new Altaxo.Graph.Gdi.CS.G2DCartesicCoordinateSystem() { ParentObject = this }; _coordinateSystem.IsXYInterchanged = isXYInterchanged; _coordinateSystem.IsXReverse = isXReversed; _coordinateSystem.UpdateAreaSize(_size); }
public DensityLegendArea(DensityLegendArea from) { this._size = from._size; this._scales = from._scales.Clone(); this._scales.ParentObject = this; this._coordinateSystem = (CS.G2DCartesicCoordinateSystem)from._coordinateSystem.Clone(); this._coordinateSystem.ParentObject = this; }
public virtual IHitTestObject HitTest(IPlotArea layer, PointD2D pt) { GraphicsPath gp = GetSelectionPath(); if (gp.IsVisible((PointF)pt)) return new HitTestObject(gp, this); else return null; }
public static IntPtr RenderEmbeddedObjectDescriptor(TYMED tymed, PointD2D graphDocumentSize) { ComDebug.ReportInfo("GraphDocumentDataObject.RenderEmbeddedObjectDescriptor"); // Brockschmidt, Inside Ole 2nd ed. page 991 if (!(tymed == TYMED.TYMED_HGLOBAL)) throw new ArgumentException(nameof(tymed) + " is not TYMED_HGLOBAL"); // Fill in the basic information. OBJECTDESCRIPTOR od = new OBJECTDESCRIPTOR(); // According to the documentation this is used just to find an icon. od.clsid = typeof(GraphDocumentEmbeddedComObject).GUID; od.dwDrawAspect = DVASPECT.DVASPECT_CONTENT; od.sizelcx = 0; // zero in imitation of Word/Excel, but could be (int)(graphDocumentSize.X * 2540 / 72.0) od.sizelcy = 0; // zero in imitation of Word/Excel, but could be (int)(graphDocumentSize.Y * 2540 / 72.0); od.pointlx = 0; od.pointly = 0; od.dwStatus = MiscStatus((int)od.dwDrawAspect); // Descriptive strings to tack on after the struct. string name = GraphDocumentEmbeddedComObject.USER_TYPE; int name_size = (name.Length + 1) * sizeof(char); string source = "Altaxo"; int source_size = (source.Length + 1) * sizeof(char); int od_size = Marshal.SizeOf(typeof(OBJECTDESCRIPTOR)); od.dwFullUserTypeName = od_size; od.dwSrcOfCopy = od_size + name_size; int full_size = od_size + name_size + source_size; od.cbSize = full_size; // To avoid 'unsafe', we will arrange the strings in a byte array. byte[] strings = new byte[full_size]; Encoding unicode = Encoding.Unicode; Array.Copy(unicode.GetBytes(name), 0, strings, od.dwFullUserTypeName, name.Length * sizeof(char)); Array.Copy(unicode.GetBytes(source), 0, strings, od.dwSrcOfCopy, source.Length * sizeof(char)); // Combine the strings and the struct into a single block of mem. IntPtr hod = Kernel32Func.GlobalAlloc(GlobalAllocFlags.GHND, full_size); if (!(hod != IntPtr.Zero)) throw new InvalidOperationException("GlobalAlloc operation was not successful"); IntPtr buf = Kernel32Func.GlobalLock(hod); Marshal.Copy(strings, 0, buf, full_size); Marshal.StructureToPtr(od, buf, false); Kernel32Func.GlobalUnlock(hod); return hod; }
public TextGraphic(PointD2D graphicPosition, string text, FontX textFont, NamedColor textColor, double Rotation) : this(graphicPosition, text, textFont, textColor) { this.Rotation = Rotation; }
public DensityImageLegend(DensityImagePlotItem plotItem, Main.IDocumentNode futureParentObject, PointD2D initialLocation, PointD2D graphicSize, Main.Properties.IReadOnlyPropertyBag context) : base(new ItemLocationDirect()) { if (null == plotItem) throw new ArgumentNullException("plotItem"); if (null == futureParentObject) throw new ArgumentNullException("futureParentObject"); this.ParentObject = futureParentObject; this.PlotItem = plotItem; if (null == this._plotItemProxy.DocumentPath) throw new ArgumentException("No path could be found between plotItem and futureParentObject. This is an indication that one of the objects is not rooted."); this.SetSize(graphicSize.X, graphicSize.Y, Main.EventFiring.Suppressed); this.SetPosition(initialLocation, Main.EventFiring.Suppressed); // _orientationIsVertical = true; // _scaleIsReversed = false; var cachedScale = (NumericalScale)PlotItem.Style.Scale.Clone(); var scaleTickSpacing = Altaxo.Graph.Scales.Scale.CreateDefaultTicks(cachedScale.GetType()); _cachedArea = new DensityLegendArea(Size, true, false, cachedScale, scaleTickSpacing); //_cachedArea.ParentObject = this; // --> moved to the end of this function _axisStyles = new AxisStyleCollection(); _axisStyles.UpdateCoordinateSystem(_cachedArea.CoordinateSystem); // _axisStyles.ParentObject = this; --> see below var sx0 = new AxisStyle(CSLineID.X0, true, true, false, "Z values", context); sx0.AxisLineStyle.FirstDownMajorTicks = true; sx0.AxisLineStyle.FirstUpMajorTicks = false; sx0.AxisLineStyle.FirstDownMinorTicks = true; sx0.AxisLineStyle.FirstUpMinorTicks = false; var sx1 = new AxisStyle(CSLineID.X1, true, false, false, null, context); sx1.AxisLineStyle.FirstDownMajorTicks = false; sx1.AxisLineStyle.FirstUpMajorTicks = false; sx1.AxisLineStyle.FirstDownMinorTicks = false; sx1.AxisLineStyle.FirstUpMinorTicks = false; var sy0 = new AxisStyle(CSLineID.Y0, true, false, false, "Color map", context); var sy1 = new AxisStyle(CSLineID.Y1, true, false, false, null, context); _axisStyles.Add(sx0); _axisStyles.Add(sx1); _axisStyles.Add(sy0); _axisStyles.Add(sy1); sx0.Title.Rotation = 90; sx0.Title.Location.ParentAnchorX = RADouble.NewRel(0); // Left sx0.Title.Location.ParentAnchorY = RADouble.NewRel(0.5); // Center sx0.Title.Location.LocalAnchorX = RADouble.NewRel(0.5); // Center sx0.Title.Location.LocalAnchorY = RADouble.NewRel(1); // Bottom sx0.Title.X = -Width / 3; sx0.Title.Y = 0; sy0.Title.Location.ParentAnchorX = RADouble.NewRel(0.5); // Center sy0.Title.Location.ParentAnchorY = RADouble.NewRel(0); // Top sy0.Title.Location.LocalAnchorX = RADouble.NewRel(0.5); // Center sy0.Title.Location.LocalAnchorY = RADouble.NewRel(1); // Bottom sy0.Title.X = 0; sy0.Title.Y = sy0.Title.Height / 2; // set the parent objects _axisStyles.ParentObject = this; _cachedArea.ParentObject = this; this.UpdateTransformationMatrix(); }
/// <summary> /// Returns the index of a scatter point that is nearest to the location <c>hitpoint</c> /// </summary> /// <param name="layer">The layer in which this plot item is drawn into.</param> /// <param name="hitpoint">The point where the mouse is pressed.</param> /// <returns>The information about the point that is nearest to the location, or null if it can not be determined.</returns> public XYScatterPointInformation GetNearestPlotPoint(IPlotArea layer, PointD2D hitpoint) { Processed2DPlotData pdata; if (null != (pdata = _cachedPlotDataUsedForPainting)) { PlotRangeList rangeList = pdata.RangeList; PointF[] ptArray = pdata.PlotPointsInAbsoluteLayerCoordinates; double mindistance = double.MaxValue; int minindex = -1; for (int i = 1; i < ptArray.Length; i++) { double distance = Math2D.SquareDistanceLineToPoint(hitpoint, ptArray[i - 1], ptArray[i]); if (distance < mindistance) { mindistance = distance; minindex = Math2D.Distance(ptArray[i - 1], hitpoint) < Math2D.Distance(ptArray[i], hitpoint) ? i - 1 : i; } } // ok, minindex is the point we are looking for // so we have a look in the rangeList, what row it belongs to int rowindex = rangeList.GetRowIndexForPlotIndex(minindex); return new XYScatterPointInformation(ptArray[minindex], rowindex, minindex); } return null; }
/// <summary> /// Test wether the mouse hits a plot item. /// </summary> /// <param name="layer">The layer in which this plot item is drawn into.</param> /// <param name="hitpoint">The point where the mouse is pressed.</param> /// <returns>Null if no hit, or a <see cref="IHitTestObject" /> if there was a hit.</returns> public override IHitTestObject HitTest(IPlotArea layer, PointD2D hitpoint) { Processed2DPlotData pdata = _cachedPlotDataUsedForPainting; if (null == pdata) return null; PlotRangeList rangeList = pdata.RangeList; PointF[] ptArray = pdata.PlotPointsInAbsoluteLayerCoordinates; if (ptArray.Length < 2) return null; if (ptArray.Length < 2048) { GraphicsPath gp = new GraphicsPath(); gp.AddLines(ptArray); if (gp.IsOutlineVisible((PointF)hitpoint, new Pen(Color.Black, 5))) { gp.Widen(new Pen(Color.Black, 5)); return new HitTestObject(gp, this); } } else // we have too much points for the graphics path, so make a hit test first { int hitindex = -1; for (int i = 1; i < ptArray.Length; i++) { if (Math2D.IsPointIntoDistance((PointF)hitpoint, 5, ptArray[i - 1], ptArray[i])) { hitindex = i; break; } } if (hitindex < 0) return null; GraphicsPath gp = new GraphicsPath(); int start = Math.Max(0, hitindex - 1); gp.AddLine(ptArray[start], ptArray[start + 1]); gp.AddLine(ptArray[start + 1], ptArray[start + 2]); gp.Widen(new Pen(Color.Black, 5)); return new HitTestObject(gp, this); } return null; }
public bool IsGripHitted(PointD2D point) { foreach (var ele in GripList) if (ele.IsGripHitted(point)) return true; return false; }
public bool GetHittedElement(PointD2D point, out IGripManipulationHandle gripHandle, out IHitTestObject hitObject) { for (int i = GripList.Count - 1; i >= 0; i--) { if (GripList[i].IsGripHitted(point)) { gripHandle = GripList[i]; hitObject = HittedList[i]; return true; } } gripHandle = null; hitObject = null; return false; }
/// <summary> /// Activates this grip, providing the initial position of the mouse. /// </summary> /// <param name="initialPosition">Initial position of the mouse.</param> /// <param name="isActivatedUponCreation">If true the activation is called right after creation of this handle. If false, /// thie activation is due to a regular mouse click in this grip.</param> public void Activate(PointD2D initialPosition, bool isActivatedUponCreation) { foreach (var ele in GripList) ele.Activate(initialPosition, isActivatedUponCreation); }
public void MoveGrip(PointD2D newPosition) { foreach (var ele in GripList) ele.MoveGrip(newPosition); }
protected void MeasureBackground(Graphics g, double textWidth, double textHeight) { var fontInfo = FontInfo.Create(g, _font); double widthOfOne_n = Glyph.MeasureString(g, "n", _font).X; double widthOfThree_M = Glyph.MeasureString(g, "MMM", _font).X; double distanceXL = 0; // left distance bounds-text double distanceXR = 0; // right distance text-bounds double distanceYU = 0; // upper y distance bounding rectangle-string double distanceYL = 0; // lower y distance if (this._background != null) { // the distance to the sides should be like the character n distanceXL = 0.25 * widthOfOne_n; // left distance bounds-text distanceXR = distanceXL; // right distance text-bounds distanceYU = fontInfo.cyDescent; // upper y distance bounding rectangle-string distanceYL = 0; // lower y distance } PointD2D size = new PointD2D((textWidth + distanceXL + distanceXR), (textHeight + distanceYU + distanceYL)); _cachedExtendedTextBounds = new RectangleD2D(PointD2D.Empty, size); RectangleD2D textRectangle = new RectangleD2D(new PointD2D(-distanceXL, -distanceYU), size); if (this._background != null) { var backgroundRect = this._background.MeasureItem(g, textRectangle); _cachedExtendedTextBounds.Offset(textRectangle.X - backgroundRect.X, textRectangle.Y - backgroundRect.Y); size = backgroundRect.Size; distanceXL = -backgroundRect.Left; distanceXR = (backgroundRect.Right - textWidth); distanceYU = -backgroundRect.Top; distanceYL = (backgroundRect.Bottom - textHeight); } //var xanchor = _location.PivotX.GetValueRelativeTo(size.X); //var yanchor = _location.PivotY.GetValueRelativeTo(size.Y); // this._leftTop = new PointD2D(-xanchor, -yanchor); ((ItemLocationDirectAutoSize)_location).SetSizeInAutoSizeMode(size, false); this._cachedTextOffset = new PointD2D(distanceXL, distanceYU); }
/// <summary> /// Test wether the mouse hits a plot item. The default implementation here returns null. /// If you want to have a reaction on mouse click on a curve, implement this function. /// </summary> /// <param name="layer">The layer in which this plot item is drawn into.</param> /// <param name="hitpoint">The point where the mouse is pressed.</param> /// <returns>Null if no hit, or a <see cref="IHitTestObject" /> if there was a hit.</returns> public virtual IHitTestObject HitTest(IPlotArea layer, PointD2D hitpoint) { return null; }