public static bool DoesLineIntersectRectangle(RectangleF pobjRectangle, Line pobjLine, ref Line pobjIntersectingPortionOfLine) { RectangleF objLineAsRectangle = default(RectangleF); objLineAsRectangle = pobjLine.ToRectangle(); if (!pobjRectangle.IntersectsWith(objLineAsRectangle)) { return false; } else { bool blnIsPointAIn = false; bool blnIsPointBIn = false; blnIsPointAIn = pobjRectangle.Contains(pobjLine.PointA); blnIsPointBIn = pobjRectangle.Contains(pobjLine.PointB); if (blnIsPointAIn && blnIsPointBIn) { pobjIntersectingPortionOfLine = pobjLine; } else { PointF[] colIntersections = new PointF[2]; // Either one or two intersections. List<Line> colLines = null; colLines = GeometryHelper.RectangleTo4Lines(pobjRectangle); foreach (Line objLine in colLines) { if (colIntersections[0].IsEmpty) { DoLinesIntersect(objLine, pobjLine, ref colIntersections[0]); } else if (colIntersections[1].IsEmpty) { DoLinesIntersect(objLine, pobjLine, ref colIntersections[1]); } } if (!blnIsPointAIn && !blnIsPointBIn) { pobjIntersectingPortionOfLine = new Line(colIntersections[0], colIntersections[1]); } else { if (blnIsPointAIn) { pobjIntersectingPortionOfLine = new Line(colIntersections[0], pobjLine.PointA); } else { pobjIntersectingPortionOfLine = new Line(colIntersections[0], pobjLine.PointB); } } } return true; } }
public bool intersects(RectangleF r) { return LineIntersectsLine(start, end, new PointD(r.X, r.Y), new PointD(r.X + r.Width, r.Y)) || LineIntersectsLine(start, end, new PointD(r.X + r.Width, r.Y), new PointD(r.X + r.Width, r.Y + r.Height)) || LineIntersectsLine(start, end, new PointD(r.X + r.Width, r.Y + r.Height), new PointD(r.X, r.Y + r.Height)) || LineIntersectsLine(start, end, new PointD(r.X, r.Y + r.Height), new PointD(r.X, r.Y)) || (r.Contains(new PointF((float)start.x, (float)start.y)) && r.Contains(new PointF((float)end.x, (float)end.y))); }
/// <summary> /// Determines whether a given point is inside and close to the edge of a given rectangle. /// </summary> /// <param name="rectangle">The rectangle within which the point should be located.</param> /// <param name="test">The point to test for.</param> /// <param name="tolerance"> /// The tolerance. This is subtracted from the bounds of the rectangle to create a border within which the /// <paramref /// name="test" /> /// point must be located. /// </param> /// <param name="toTest">The edges that should be tested.</param> /// <returns>A combination of Edge flags depending on which edges the point is close to.</returns> internal static Edge IsPointOnEdge( RectangleF rectangle, PointF test, float tolerance, EdgeTest toTest ) { // If the point is not within the rectangle, then there is no need for further tests. if( !rectangle.Contains( test ) ) { return Edge.None; } Edge result = Edge.None; // Test vertical edges. if( ( toTest & EdgeTest.Vertical ) != 0 ) { if( test.Y >= rectangle.Y && test.Y <= rectangle.Y + tolerance ) { result |= Edge.Top; } if( test.Y <= rectangle.Y + rectangle.Height && test.Y >= rectangle.Y + rectangle.Height - tolerance ) { result |= Edge.Bottom; } } // Test horizontal edges. if( ( toTest & EdgeTest.Horizontal ) != 0 ) { if( test.X <= rectangle.X + rectangle.Width && test.X >= rectangle.X + rectangle.Width - tolerance ) { result |= Edge.Right; } if( test.X >= rectangle.X && test.X <= rectangle.X + tolerance ) { result |= Edge.Left; } } return result; }
/// <summary> /// Tiles path text inside a rectangle /// </summary> static private Path TilePathText(Path pathText, RectangleF rect, float offset) { var textBounds = pathText.GetBounds(); pathText.ApplyTransform(CreateTranslateMatrix(rect.X - textBounds.Left, rect.Y - textBounds.Top)); var tiledText = new Path(); using (var firstLine = new Path()) { while (rect.Contains(pathText.GetBounds())) { firstLine.DrawPath(pathText); pathText.ApplyTransform(CreateTranslateMatrix(textBounds.Width + offset, 0)); } float lineOffset = textBounds.Width / 2; if (firstLine.Points.Count == 0) { return(tiledText); } while (rect.Bottom > firstLine.GetBounds().Bottom) { tiledText.DrawPath(firstLine); firstLine.ApplyTransform(CreateTranslateMatrix(lineOffset, textBounds.Height + offset)); lineOffset *= -1; } return(tiledText); } }
protected virtual void KeyboardDidShowNotification(NSNotification notification) { UIView activeView = KeyboardGetActiveView(); if (activeView == null) return; ((UITextField)activeView).ShowDoneButtonOnKeyboard(); UIScrollView scrollView = activeView.FindSuperviewOfType(this.View, typeof(UIScrollView)) as UIScrollView; if (scrollView == null) return; RectangleF keyboardBounds = UIKeyboard.BoundsFromNotification(notification); UIEdgeInsets contentInsets = new UIEdgeInsets(0.0f, 0.0f, keyboardBounds.Size.Height, 0.0f); scrollView.ContentInset = contentInsets; scrollView.ScrollIndicatorInsets = contentInsets; // If activeField is hidden by keyboard, scroll it so it's visible RectangleF viewRectAboveKeyboard = new RectangleF(this.View.Frame.Location, new SizeF(this.View.Frame.Width, this.View.Frame.Size.Height - keyboardBounds.Size.Height)); RectangleF activeFieldAbsoluteFrame = activeView.Superview.ConvertRectToView(activeView.Frame, this.View); // activeFieldAbsoluteFrame is relative to this.View so does not include any scrollView.ContentOffset // Check if the activeField will be partially or entirely covered by the keyboard if (!viewRectAboveKeyboard.Contains(activeFieldAbsoluteFrame)) { // Scroll to the activeField Y position + activeField.Height + current scrollView.ContentOffset.Y - the keyboard Height PointF scrollPoint = new PointF(0.0f, activeFieldAbsoluteFrame.Location.Y + activeFieldAbsoluteFrame.Height + scrollView.ContentOffset.Y - viewRectAboveKeyboard.Height); scrollView.SetContentOffset(scrollPoint, true); } }
public void ContainsF () { // from bug #5985 RectangleF outer = new RectangleF (100, 150, 300, 300); RectangleF inner = new RectangleF (139.3323f, 188.4053f, 140.2086f, 210.3129f); Assert.IsTrue (outer.Contains (inner), "a"); }
public RectangleD(RectangleF outer, RectangleF inner) { if (!outer.Contains(inner)) throw new ArgumentOutOfRangeException(nameof(inner), nameof(outer) + " must contain " + nameof(inner)); this.Inner = inner; this.Outer = outer; }
/// <summary> /// Check if a given rectangle would be selected by another rectangle. /// By default, checks whether the selection rectangle intersects with the bounding rectangle. /// If Alt is pressed, the selection rectangle has to contain the complete bounding rectangle. /// </summary> /// <param name="selectionRectangle">The rectangle that represents the selection.</param> /// <param name="boundingRectangle">The rectangle that should be tested whether it is selected.</param> /// <param name="modifierKeys">The modifier keys that are currently pressed.</param> /// <returns> /// <see langword="true" /> if the rectangle is selected; <see langword="false" /> otherwise. /// </returns> public static bool IsSelected( RectangleF selectionRectangle, RectangleF boundingRectangle, Keys modifierKeys ) { if( ( modifierKeys & Keys.Alt ) != 0 ) { return selectionRectangle.Contains( boundingRectangle ); } else { return selectionRectangle.IntersectsWith( boundingRectangle ); } }
internal override bool Hit(PointF p) { RectangleF r = new RectangleF(p, new SizeF(0,0)); RectangleF env = new RectangleF(this.mCurrentPoint,new SizeF(10,10)); env.Offset(-5,-5); mHovered = env.Contains(r); //Debug.WriteLine("(" + p.X + "," + p.Y + ") c " + "(" + mCurrentPoint.X + "," + mCurrentPoint.Y +")"); return mHovered; }
/// <summary> /// Initializes a new instance of the <see cref="Simulation" /> class. /// </summary> /// <param name="teams">The teams to be played against each other.</param> /// <param name="ball">The ball.</param> /// <param name="pitchBounds">The pitch boundaries.</param> /// <param name="friction">The friction coefficient.</param> public Simulation(ReadOnlyCollection<Team> teams, PointMass ball, RectangleF pitchBounds, float friction) { Contract.Requires<ArgumentNullException>(teams != null); Contract.Requires<ArgumentNullException>(ball != null); Contract.Requires<ArgumentException>(friction >= 0); Contract.Requires<ArgumentException>(pitchBounds.Width > 0 && pitchBounds.Height > 0); Contract.Requires<ArgumentException>(Contract.ForAll(teams, t => t != null && pitchBounds.IntersectsOrBorders(t.GoalBounds) && t.Players.All(p => pitchBounds.Contains(p.Position)))); Contract.Requires<ArgumentException>(pitchBounds.Contains(ball.Position)); _simulate = SimulatePlaying; _teams = teams; _startingPositions = (from t in teams select (from p in t.Players select p.Position).ToList().AsReadOnly()).ToList().AsReadOnly(); _ball = ball; _ballStartingPosition = ball.Position; PitchBounds = pitchBounds; Friction = friction; }
public RectangleD(RectangleF outer, RectangleF inner) { if (!outer.Contains(inner)) { throw new ArgumentOutOfRangeException("inner", "Outer RectangleF must contain Inner RectangleF"); } this.Inner = inner; this.Outer = outer; }
public override GH_ObjectResponse RespondToMouseDown(GH_Canvas sender, GH_CanvasMouseEvent e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { System.Drawing.RectangleF rec = ButtonBounds; if (rec.Contains(e.CanvasLocation)) { MessageBox.Show("The button was clicked", "Button", MessageBoxButtons.OK); return(GH_ObjectResponse.Handled); } } return(base.RespondToMouseDown(sender, e)); }
/// <summary> /// Initializes a new instance of the <see cref="Simulation" /> class. /// </summary> /// <param name="teams">The teams to be played against each other.</param> /// <param name="ball">The ball.</param> /// <param name="pitchBounds">The pitch boundaries.</param> /// <param name="friction">The friction coefficient.</param> public Simulation(ReadOnlyCollection<Team> teams, PointMass ball, RectangleF pitchBounds, float friction) { Contract.Requires<ArgumentNullException>(teams != null); Contract.Requires<ArgumentNullException>(ball != null); Contract.Requires<ArgumentException>(friction >= 0); Contract.Requires<ArgumentException>(pitchBounds.Width > 0 && pitchBounds.Height > 0); Contract.Requires<ArgumentException>(Contract.ForAll(teams, t => t != null && t.IsValid(pitchBounds))); Contract.Requires<ArgumentException>(pitchBounds.Contains(ball.Position)); _simulate = SimulatePlaying; _teams = teams; _startingPositions = from t in teams select t.PlayerPositions; _ball = ball; _ballStartingPosition = ball.Position; PitchBounds = pitchBounds; Friction = friction; }
private Node GetNodAtXYRec(Node nod, int x, int y, int mouseX, int mouseY, bool parentIsExpanded) { int cY = y + rowHeight * crtNodCheck; int cX = x; float yT = cY; RectangleF r = new RectangleF(cX, yT, size.Width, rowHeight); if (r.Contains(mouseX, mouseY)) { nodDblX = location.X + x + EXPANDER_SIZE; nodDblY = location.Y + nodesDrawingTopPosition + crtNodCheck * rowHeight; return nod; } if (nod.IsExpanded) { x += TAB_NOD_SIZE; } for (int i = 0; i < nod.Nodes.Count; i++) { Node ndr = null; if (parentIsExpanded) crtNodCheck++; ndr = GetNodAtXYRec(nod.Nodes[i], x, y, mouseX, mouseY, parentIsExpanded && nod.Nodes[i].IsExpanded); if (ndr != null) { nodDblX = location.X + x + LEFT_PADDING; nodDblY = location.Y + nodesDrawingTopPosition + crtNodCheck * rowHeight; return ndr; } } return null; }
/// <summary> /// 指定の座標値に駒台上の駒があればそれを取得します。 /// </summary> private BoardPiece PointToHandPiece(System.Drawing.Point pos) { var boxTypeN = PointToPieceBoxType(pos); if (boxTypeN == null) { return null; } var boxType = boxTypeN.Value; foreach (var pieceType in EnumEx.GetValues<PieceType>()) { var center = HandPieceToPoint(pieceType, boxType); var rect = new RectangleF( (float)(center.X - SquareSize.Width / 2), (float)(center.Y - SquareSize.Height / 2), SquareSize.Width, SquareSize.Height); if (rect.Contains(pos)) { return new BoardPiece(pieceType, false, boxType); } } return null; }
private void rendererControl_MouseDown(object sender, MouseEventArgs e) { Skin skin = _lastSkin; if (skin == null) return; CheckMouse(e.Y); float halfWidth = Renderer.Width / 2.0f; float halfImgWidth = 56.0f / 2.0f; var rect = new RectangleF(halfWidth - halfImgWidth, 0, halfImgWidth * 2, 22); _mousePoint = e.Location; if (rect.Contains(e.Location)) { if (splitContainer4.SplitterDistance == 0) _opening = true; else _opening = false; _animTimer.Start(); return; } _mouseIsDown = true; //_isValidPick = GetPick(e.X, e.Y, ref _pickPosition); using (var backup = new ColorGrabber(GlobalDirtiness.CurrentSkin, skin.Width, skin.Height)) { backup.Load(); try { if (e.Button == MouseButtons.Left) { if (_isValidPick) _selectedTool.Tool.BeginClick(_lastSkin, _pickPosition, e); else _selectedTool.Tool.BeginClick(_lastSkin, new Point(-1, -1), e); UseToolOnViewport(e.X, e.Y); } else _tools[(int)Tools.Camera].Tool.BeginClick(_lastSkin, Point.Empty, e); } catch (Exception ex) { backup.Save(); this.saveAllToolStripMenuItem_Click(null, null); throw ex; } } }
private void DrawGLToolbar() { // 2D Setup2D(new Rectangle(0, 0, Renderer.Width, Renderer.Height)); TextureGL.Unbind(); GL.Enable(EnableCap.Blend); float halfWidth = Renderer.Width / 2.0f; float halfImgWidth = 56.0f / 2.0f; var rect = new RectangleF(halfWidth - halfImgWidth, 0, halfImgWidth * 2, 22); Texture img = (splitContainer4.SplitterDistance == 0) ? _toolboxDownNormal : _toolboxUpNormal; if (rect.Contains(_mousePoint)) GL.Color4((byte) 255, (byte) 255, (byte) 255, (byte) 255); else GL.Color4((byte) 255, (byte) 255, (byte) 255, (byte) 64); img.Bind(); const float widSep = 56.0f / 64.0f; const float heiSep = 22.0f / 32.0f; GL.Begin(BeginMode.Quads); GL.TexCoord2(0, 0); GL.Vertex2(halfWidth - halfImgWidth, -1); GL.TexCoord2(widSep, 0); GL.Vertex2(halfWidth + halfImgWidth, -1); GL.TexCoord2(widSep, heiSep); GL.Vertex2(halfWidth + halfImgWidth, 21); GL.TexCoord2(0, heiSep); GL.Vertex2(halfWidth - halfImgWidth, 21); GL.End(); }
/// <summary> /// Check if this PSystem's region overlaps given rectangle /// </summary> /// <param name="rect">RectangleF to be checked</param> /// <returns>True if each rectangle overlaps other rectangle /// (doesn't contain whole rectangle)</returns> public virtual bool Overlaps(RectangleF rect) { if (this.Rect.Contains(rect) && rect.Contains(this.Rect)) return true; else if (this.Rect.IntersectsWith(rect) && !(this.Rect.Contains(rect) || rect.Contains(this.Rect))) return true; else return false; }
protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e) { float yPos = 1; int curItem = firstItem; float itemHeight = ItemHeight; while (curItem < completionData.Length && yPos < Height) { RectangleF drawingBackground = new RectangleF(1, yPos, Width - 2, itemHeight); if (drawingBackground.Contains(e.X, e.Y)) { SelectIndex(curItem); break; } yPos += itemHeight; ++curItem; } }
private void gvChat_MouseMove(object sender, MouseEventArgs e) { try { GridHitInfo info = (sender as GridView).CalcHitInfo(e.X, e.Y); if (info.InRow && this.ChatRowPoints.ContainsKey(info.RowHandle)) { Rectangle rectangle = this.ChatRowPoints[info.RowHandle]; if (rectangle.Contains(e.X, e.Y)) { ChatLine row = (sender as GridView).GetRow(info.RowHandle) as ChatLine; if (row != null) { IText text = row.TextSegments[0]; if (text != null) { int index; Font textFont = text.TextFont; string str = text.Text; string str2 = null; Dictionary<int, ChatLink> dictionary = null; List<string> list = null; List<MultiVal<int, int>> list2 = null; SortedList<int, Emote> list3 = null; if (!(!Program.Settings.Chat.Links.ShowChatLinks || (!row.ContainsLinks.HasValue ? false : !row.ContainsLinks.Value))) { dictionary = ChatLink.CreateCharacterIndex(ChatLink.FindLinks(str)); } if (!(!Program.Settings.Chat.Emotes.ShowEmotes || (!row.ContainsEmotes.HasValue ? false : !row.ContainsEmotes.Value))) { list = new List<string>(); list2 = new List<MultiVal<int, int>>(); list3 = new SortedList<int, Emote>(); foreach (Emote emote in Emote.AllEmotes.Values) { index = str.IndexOf(emote.CharSequence); while (index >= 0) { bool flag = false; if (dictionary != null) { foreach (ChatLink link in dictionary.Values) { if ((index > link.StartIndex) && (index < link.EndIndex)) { flag = true; } } } if (!flag) { list2.Add(new MultiVal<int, int>(index, emote.CharSequence.Length)); list3.Add(index, emote); } index = str.IndexOf(emote.CharSequence, (int) (index + emote.CharSequence.Length)); if (!(!Program.Settings.Chat.Links.ShowChatLinks || (!row.ContainsLinks.HasValue ? false : !row.ContainsLinks.Value))) { if (str2 == null) { str2 = str; } str2 = str2.Replace(emote.CharSequence, ""); } } } } using (Graphics graphics = this.gpgChatGrid.CreateGraphics()) { float num6; float x; float y; int num9; int num10; ChatLink link2; SolidBrush brush; string[] strArray; int num11; SizeF ef; Brush brush2; Font font2; RectangleF ef2; if ((list3 != null) && (list3.Count > 0)) { int num2; list2.Add(new MultiVal<int, int>(str.Length, 0)); list3.Add(str.Length, null); SortedList<int, MultiVal<int, int>> list4 = new SortedList<int, MultiVal<int, int>>(list2.Count); list4[-1] = new MultiVal<int, int>(0, 0); foreach (MultiVal<int, int> val in list2) { list4[val.Value1] = val; } for (num2 = 1; num2 < list4.Count; num2++) { int num3 = list4.Values[num2 - 1].Value1; index = list4.Values[num2].Value1; int num4 = list4.Values[num2 - 1].Value2; int num5 = list4.Values[num2].Value2; list.Add(str.Substring(num3 + num4, index - (num3 + num4))); } dictionary = ChatLink.CreateCharacterIndex(ChatLink.FindLinks(str2)); num6 = textFont.Height + 3; x = rectangle.X; y = rectangle.Y; num9 = (this.colText.VisibleWidth - 10) + rectangle.X; num10 = 0; link2 = null; using (brush = new SolidBrush(text.TextColor)) { for (num2 = 0; num2 < list.Count; num2++) { if (list[num2].Length > 0) { strArray = DrawUtil.SplitString(list[num2], " "); for (num11 = 0; num11 < strArray.Length; num11++) { if (link2 == null) { if ((dictionary.Count > 0) && dictionary.ContainsKey(num10)) { link2 = dictionary[num10]; } if (link2 != null) { using (brush2 = new SolidBrush(link2.LinkColor)) { using (font2 = new Font(textFont, FontStyle.Underline)) { ef = DrawUtil.MeasureString(graphics, link2.DisplayText + " ", font2); if (((ef.Width <= (num9 - rectangle.Left)) || (x != rectangle.Left)) && ((x + ef.Width) > num9)) { x = rectangle.X; y += num6; } ef2 = new RectangleF(x, y, ef.Width, ef.Height); if (ef2.Contains((float) e.X, (float) e.Y)) { this.Cursor = Cursors.Hand; return; } } } } else { ef = DrawUtil.MeasureString(graphics, strArray[num11], textFont); if (((ef.Width <= (num9 - rectangle.Left)) || (x != rectangle.Left)) && ((x + ef.Width) > num9)) { x = rectangle.X; y += num6; } } num10 += strArray[num11].Length; x += ef.Width; } else { num10 += strArray[num11].Length; } if ((link2 != null) && (num10 >= link2.EndIndex)) { link2 = null; } } } if (list3.Values[num2] != null) { float num12 = ((float) textFont.Height) / ((float) list3.Values[num2].Image.Height); float num13 = list3.Values[num2].Image.Width * num12; if ((x + num13) > num9) { x = rectangle.X; y += num6; } x += num13; } } } } else { dictionary = ChatLink.CreateCharacterIndex(ChatLink.FindLinks(str)); if ((dictionary != null) && (dictionary.Count > 0)) { num6 = textFont.Height + 3; x = rectangle.X; y = rectangle.Y; num9 = (this.colText.VisibleWidth - 10) + rectangle.X; num10 = 0; link2 = null; using (brush = new SolidBrush(text.TextColor)) { strArray = DrawUtil.SplitString(str, " "); for (num11 = 0; num11 < strArray.Length; num11++) { if (link2 == null) { if ((dictionary.Count > 0) && dictionary.ContainsKey(num10)) { link2 = dictionary[num10]; } if (link2 != null) { using (brush2 = new SolidBrush(link2.LinkColor)) { using (font2 = new Font(textFont, FontStyle.Underline)) { ef = DrawUtil.MeasureString(graphics, link2.DisplayText + " ", font2); if (((ef.Width <= (num9 - rectangle.Left)) || (x != rectangle.Left)) && ((x + ef.Width) > num9)) { x = rectangle.X; y += num6; } ef2 = new RectangleF(x, y, ef.Width, ef.Height); if (ef2.Contains((float) e.X, (float) e.Y)) { this.Cursor = Cursors.Hand; return; } } } } else { ef = DrawUtil.MeasureString(graphics, strArray[num11], textFont); if (((ef.Width <= (num9 - rectangle.Left)) || (x != rectangle.Left)) && ((x + ef.Width) > num9)) { x = rectangle.X; y += num6; } } num10 += strArray[num11].Length; x += ef.Width; } else { num10 += strArray[num11].Length; } if ((link2 != null) && (num10 >= link2.EndIndex)) { link2 = null; } } } } } } } } } } } catch (Exception exception) { ErrorLog.WriteLine(exception); this.Cursor = Cursors.Default; } this.Cursor = Cursors.Default; }
/// <summary> /// Determines whether this instance can start sliding given the touch position and the /// current location/size of the top view. /// Note that touchPosition is in Screen coordinate. /// </summary> /// <returns>true</returns> /// <c>false</c> /// <param name="touchPosition">Touch position.</param> /// <param name="topViewCurrentFrame">Top view's current frame.</param> public override bool CanStartSliding(PointF touchPosition, RectangleF topViewCurrentFrame) { if (!IsVisible) { return (touchPosition.X >= View.Bounds.Size.Width - EdgeTolerance && touchPosition.X <= View.Bounds.Size.Width); } else { return topViewCurrentFrame.Contains (touchPosition); } }
public bool Contains(RectangleF r) { return(this.Contains(r.Location) && r.Contains(new Point((int)r.Right, (int)r.Bottom))); }
public override GH_ObjectResponse RespondToMouseUp(GH_Canvas sender, GH_CanvasMouseEvent e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { GH_Component comp = Owner as GH_Component; if (dragY) { // if drag was true then we release it here: scrollStartY += deltaY; deltaY = 0; dragY = false; comp.ExpireSolution(true); return(GH_ObjectResponse.Release); } if (dragX) { // if drag was true then we release it here: scrollStartX += deltaX; deltaX = 0; dragX = false; comp.ExpireSolution(true); return(GH_ObjectResponse.Release); } for (int i = 0; i < dropdownlists.Count; i++) { System.Drawing.RectangleF rec = BorderBound[i]; if (rec.Contains(e.CanvasLocation)) { unfolded[i] = !unfolded[i]; // close any other dropdowns that may be unfolded for (int j = 0; j < unfolded.Count; j++) { if (j == i) { continue; } unfolded[j] = false; } comp.ExpireSolution(true); return(GH_ObjectResponse.Handled); } if (unfolded[i]) { System.Drawing.RectangleF rec2 = dropdownBound[i]; if (rec2.Contains(e.CanvasLocation)) { for (int j = 0; j < dropdownBounds[i].Count; j++) { System.Drawing.RectangleF rec3 = dropdownBounds[i][j]; if (rec3.Contains(e.CanvasLocation)) { if (displayTexts[i] != dropdownlists[i][j]) { // record an undo event so that user can ctrl + z comp.RecordUndoEvent("Selected " + dropdownlists[i][j]); // change the displayed text on canvas displayTexts[i] = dropdownlists[i][j]; // if initial texts exists then change all dropdowns below this one to the initial description if (initialTxts != null) { for (int k = i + 1; k < dropdownlists.Count; k++) { displayTexts[k] = initialTxts[k]; } } // send the selected item back to component (i = dropdownlist index, j = selected item in that list) action(i, j); // close the dropdown unfolded[i] = !unfolded[i]; // recalculate component comp.ExpireSolution(true); } else { unfolded[i] = !unfolded[i]; comp.ExpireSolution(true); } return(GH_ObjectResponse.Handled); } } } else { unfolded[i] = !unfolded[i]; comp.ExpireSolution(true); return(GH_ObjectResponse.Handled); } } } } return(base.RespondToMouseUp(sender, e)); }
/// <summary> /// Method that find the node for which the expander was triggered /// </summary> /// <param name="node"> the node to be checked</param> /// <param name="nodeLevel"> the level of the node</param> /// <param name="crtExpanderRow"> the row associated with the node</param> /// <param name="insideClickPoint">the location inside the structure where de mouse was clicked</param> /// <param name="parentIsExpanded">true if parent node is expanded, false otherwhise</param> /// <returns></returns> private Node RecursiveExpanderCheck(Node node, int nodeLevel, ref int crtExpanderRow, Point insideClickPoint, bool parentIsExpanded) { int cY = rowHeight * crtExpanderRow + nodesDrawingTopPosition - location.Y + TITLE_OFFSET; RectangleF rowRectangleToCheck = new RectangleF(LEFT_PADDING, cY, EXPANDER_SIZE, EXPANDER_SIZE); if (!node.IsLeaf) { if (node.Parent != null && node.Parent.IsExpanded) { rowRectangleToCheck.Offset(nodeLevel * TAB_NOD_SIZE, 0); } if (rowRectangleToCheck.Contains(insideClickPoint)) return node; foreach (Node childNode in node.Nodes) { Node ndr = null; if (parentIsExpanded) { crtExpanderRow++; } ndr = RecursiveExpanderCheck(childNode, nodeLevel + 1, ref crtExpanderRow, insideClickPoint, parentIsExpanded && childNode.IsExpanded); if (ndr != null) return ndr; } } return null; }
///<summary>Returns the index in the DocsInMount array of the given location (relative to the upper left-hand corner of the pictureBoxMain control) or -1 if the location is outside all documents in the current mount. A mount must be currently selected to call this function.</summary> private int GetIdxAtMountLocation(Point location) { PointF relativeLocation=new PointF( (location.X-PointTranslation.X)/(ZoomImage*ZoomOverall)+MountSelected.Width/2, (location.Y-PointTranslation.Y)/(ZoomImage*ZoomOverall)+MountSelected.Height/2); //Enumerate the image locations. for(int i=0;i<MountItemsForSelected.Count;i++) { RectangleF itemLocation=new RectangleF(MountItemsForSelected[i].Xpos,MountItemsForSelected[i].Ypos, MountItemsForSelected[i].Width,MountItemsForSelected[i].Height); if(itemLocation.Contains(relativeLocation)) { return i; } } return -1;//No document selected in the current mount. }
/// <summary> /// Find the object that lies closest to the specified mouse (screen) point. /// </summary> /// <remarks> /// This method will search through all of the graph objects, such as /// <see cref="Axis"/>, <see cref="Legend"/>, <see cref="PaneBase.Title"/>, /// <see cref="GraphObj"/>, and <see cref="CurveItem"/>. /// If the mouse point is within the bounding box of the items (or in the case /// of <see cref="ArrowObj"/> and <see cref="CurveItem"/>, within /// <see cref="Default.NearestTol"/> pixels), then the object will be returned. /// You must check the type of the object to determine what object was /// selected (for example, "if ( object is Legend ) ..."). The /// <see paramref="index"/> parameter returns the index number of the item /// within the selected object (such as the point number within a /// <see cref="CurveItem"/> object. /// </remarks> /// <param name="mousePt">The screen point, in pixel coordinates.</param> /// <param name="g"> /// A graphic device object to be drawn into. This is normally e.Graphics from the /// PaintEventArgs argument to the Paint() method. /// </param> /// <param name="nearestObj">A reference to the nearest object to the /// specified screen point. This can be any of <see cref="Axis"/>, /// <see cref="Legend"/>, <see cref="PaneBase.Title"/>, /// <see cref="TextObj"/>, <see cref="ArrowObj"/>, or <see cref="CurveItem"/>. /// Note: If the pane title is selected, then the <see cref="GraphPane"/> object /// will be returned. /// </param> /// <param name="index">The index number of the item within the selected object /// (where applicable). For example, for a <see cref="CurveItem"/> object, /// <see paramref="index"/> will be the index number of the nearest data point, /// accessible via <see cref="CurveItem.Points">CurveItem.Points[index]</see>. /// index will be -1 if no data points are available.</param> /// <returns>true if an object was found, false otherwise.</returns> /// <seealso cref="FindNearestObject"/> public bool FindNearestObject( PointF mousePt, Graphics g, out object nearestObj, out int index ) { nearestObj = null; index = -1; // Make sure that the axes & data are being drawn if ( AxisRangesValid() ) { float scaleFactor = CalcScaleFactor(); //int hStack; //float legendWidth, legendHeight; RectangleF tmpRect; GraphObj saveGraphItem = null; int saveIndex = -1; ZOrder saveZOrder = ZOrder.H_BehindAll; // Calculate the chart rect, deducting the area for the scales, titles, legend, etc. RectangleF tmpChartRect = CalcChartRect( g, scaleFactor ); // See if the point is in a GraphObj // If so, just save the object and index so we can see if other overlying objects were // intersected as well. if ( this.GraphObjList.FindPoint( mousePt, this, g, scaleFactor, out index ) ) { saveGraphItem = this.GraphObjList[index]; saveIndex = index; saveZOrder = saveGraphItem.ZOrder; } // See if the point is in the legend if ( saveZOrder <= ZOrder.B_BehindLegend && this.Legend.FindPoint( mousePt, this, scaleFactor, out index ) ) { nearestObj = this.Legend; return true; } // See if the point is in the Pane Title if ( saveZOrder <= ZOrder.H_BehindAll && _title._isVisible ) { SizeF size = _title._fontSpec.BoundingBox( g, _title._text, scaleFactor ); tmpRect = new RectangleF( ( _rect.Left + _rect.Right - size.Width ) / 2, _rect.Top + _margin.Top * scaleFactor, size.Width, size.Height ); if ( tmpRect.Contains( mousePt ) ) { nearestObj = this; return true; } } float left = tmpChartRect.Left; // See if the point is in one of the Y Axes for ( int yIndex = 0; yIndex < _yAxisList.Count; yIndex++ ) { Axis yAxis = _yAxisList[yIndex]; float width = yAxis._tmpSpace; if ( width > 0 ) { tmpRect = new RectangleF( left - width, tmpChartRect.Top, width, tmpChartRect.Height ); if ( saveZOrder <= ZOrder.D_BehindAxis && tmpRect.Contains( mousePt ) ) { nearestObj = yAxis; index = yIndex; return true; } left -= width; } } left = tmpChartRect.Right; // See if the point is in one of the Y2 Axes for ( int yIndex = 0; yIndex < _y2AxisList.Count; yIndex++ ) { Axis y2Axis = _y2AxisList[yIndex]; float width = y2Axis._tmpSpace; if ( width > 0 ) { tmpRect = new RectangleF( left, tmpChartRect.Top, width, tmpChartRect.Height ); if ( saveZOrder <= ZOrder.D_BehindAxis && tmpRect.Contains( mousePt ) ) { nearestObj = y2Axis; index = yIndex; return true; } left += width; } } // See if the point is in the X Axis tmpRect = new RectangleF( tmpChartRect.Left, tmpChartRect.Bottom, tmpChartRect.Width, _rect.Bottom - tmpChartRect.Bottom ); if ( saveZOrder <= ZOrder.D_BehindAxis && tmpRect.Contains( mousePt ) ) { nearestObj = this.XAxis; return true; } CurveItem curve; // See if it's a data point if ( saveZOrder <= ZOrder.E_BehindCurves && FindNearestPoint( mousePt, out curve, out index ) ) { nearestObj = curve; return true; } if ( saveGraphItem != null ) { index = saveIndex; nearestObj = saveGraphItem; return true; } } return false; }
public override bool IsClicked(Point pos) { // Create an array containing all the points in the path Point[] pathPoints = new Point[points.Count + 1]; pathPoints[0] = location; Array.Copy(points.ToArray(), 0, pathPoints, 1, points.Count); // Loop through all the line segments and check if `pos` is close enough to one of them for(int i = 0; i < pathPoints.Length - 1; ++i) { RectangleF bounds = new RectangleF( new Point(Math.Min(pathPoints[i].X, pathPoints[i + 1].X), Math.Min(pathPoints[i].Y, pathPoints[i + 1].Y)), new Size(Math.Abs(pathPoints[i].X - pathPoints[i + 1].X), Math.Abs(pathPoints[i].Y - pathPoints[i + 1].Y))); bounds.Inflate(ALLOWED_ERROR + penWidth / 2, ALLOWED_ERROR + penWidth / 2); if(bounds.Contains(pos) && LayerLine.DistanceToLine(pathPoints[i], pathPoints[i + 1], pos) < ALLOWED_ERROR + penWidth / 2) return true; } // No line segment found that is close enough, so we return false return false; }
private static bool _ProcessControl(PointF mousePosition, Control control, bool ignore_rect) { // ignore_rect will call mouse_up & mouse_move in any case. var c_location = control.PointToScreen(System.Drawing.Point.Empty); var clientRect = new System.Drawing.RectangleF(c_location.X, c_location.Y, control.Width, control.Height); var contains = clientRect.Contains(mousePosition); if (contains && (mouseEvent == MouseEvents.Down) || mouseEvent == MouseEvents.Up) { if (control.Parent != null) { bool ok = true; var clickedControl = _ParentContains(control, mousePosition, control, ref ok); if (clickedControl != null && ok == false) { control = clickedControl; } } } if (ignore_rect || contains) { var client_mpos = control.PointToClient(new Point((int)mousePosition.X, (int)mousePosition.Y)); if (mousePositionChanged) { var m_args = new MouseEventArgs(MouseButtons.None, 0, (int)client_mpos.X, (int)client_mpos.Y, 0); if (dragData != null) { dragndrop = true; } //else //control.RaiseOnMouseMove(m_args); } if (!contains && mouseEvent != MouseEvents.Up) { return(true); } switch (mouseEvent) { case MouseEvents.Down: var md_args = new MouseEventArgs(mouseButton, 1, (int)client_mpos.X, (int)client_mpos.Y, 0); control.RaiseOnMouseDown(md_args); mouseLastClickControl = control; return(true); case MouseEvents.Up: if (dragndrop) { if (control.AllowDrop) { DataObject dnd_data = new DataObject(dragData); DragEventArgs dnd_args = new DragEventArgs(dnd_data, 0, (int)client_mpos.X, (int)client_mpos.Y, DragDropEffects.None, dragControlEffects); control.RaiseOnDragDrop(dnd_args); } dragData = null; dragndrop = false; return(true); } var mu_args = new MouseEventArgs(mouseButton, 1, (int)client_mpos.X, (int)client_mpos.Y, 0); control.RaiseOnMouseUp(mu_args); if (mouseLastClickControl == control) { control.RaiseOnMouseClick(mu_args); } if (mouseLastClickControl != null && control != mouseLastClickControl) { mouseLastClickControl.RaiseOnMouseUp(mu_args); } return(true); case MouseEvents.DoubleClick: var mdc_args = new MouseEventArgs(mouseButton, 2, (int)client_mpos.X, (int)client_mpos.Y, 0); control.RaiseOnMouseDoubleClick(mdc_args); return(true); case MouseEvents.Wheel: var mw_args = new MouseEventArgs(MouseButtons.Middle, 0, (int)client_mpos.X, (int)client_mpos.Y, (int)(-mouseWheelDelta * 4)); control.RaiseOnMouseWheel(mw_args); return(true); } } if (!contains) { control.RaiseOnMouseLeave(null); } return(false); }
private IVideo GetMouseOverVideo() { // handle no videos displayed if (Items.Count == 0) return null; using (Graphics g = CreateGraphics()) { const int LEFT_MARGIN = HORIZONTAL_INSET + THUMBNAIL_IMAGE_WIDTH + HORIZONTAL_INSET; int maxItemsDisplayed = Height / ItemHeight; int itemsDisplayed = Math.Min(maxItemsDisplayed, Items.Count - TopIndex); for (int i = 0; i < itemsDisplayed; i++) { // get the current video IVideo currentVideo = Items[TopIndex + i] as IVideo; // see if the mouse lies in the video's title range PointF titleLocation = new Point(LEFT_MARGIN, (i * ItemHeight) + VERTICAL_INSET); SizeF titleSize = g.MeasureString(currentVideo.Title, Font, Width - Convert.ToInt32(titleLocation.X)); RectangleF titleRectangle = new RectangleF(titleLocation, titleSize); if (titleRectangle.Contains(_lastMouseLocation)) { return currentVideo; } }; // wasn't in hyperlink return null; } }
/// <summary> /// Handles the drawing and updating of the graph. /// </summary> protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); // calculate the mouse position in the graph PointF graphMousePos = _nodeLayoutManager.ViewToGraph(_lastMousePosition); // when the layout was changed it needs to be recalculated bool layoutChanged = _nodeLayoutManager.LayoutChanged; if (layoutChanged) { _nodeLayoutManager.UpdateLayout(e.Graphics, _forceChangeLayout); _forceChangeLayout = false; } // center the root behaviour if requested if (_pendingCenterBehavior) { _pendingCenterBehavior = false; CenterNode(_rootNodeView); } // select the pending node if (_selectedNodePending != null) { if (_selectedNodePendingParent != null) { if (_selectedNodePendingParent.CanBeExpanded() && !_selectedNodePendingParent.IsExpanded) { _selectedNodePendingParent.IsExpanded = true; LayoutChanged(); } SelectedNode = _selectedNodePendingParent.GetChild(_selectedNodePending); } else { SelectedNode = RootNodeView.FindNodeViewData(_selectedNodePending); } if (SelectedNode != null) { if (SelectedNode.CanBeExpanded() && !SelectedNode.IsExpanded) { SelectedNode.IsExpanded = true; LayoutChanged(); } SelectedNode.SelectedSubItem = SelectedNode.GetSubItem(_selectedAttachmentPending); ShowNode(SelectedNode); } _selectedNodePending = null; _selectedNodePendingParent = null; _selectedAttachmentPending = null; if (ClickEvent != null) { ClickEvent(SelectedNode); } } // check if we must keep the original position of the mouse if (_maintainMousePosition) { _maintainMousePosition = false; // move the graph so that _graphOrigin is at the same position in the view as it was before float mouseX = (graphMousePos.X - _graphOrigin.X) * _nodeLayoutManager.Scale + _nodeLayoutManager.Offset.X; float mouseY = (graphMousePos.Y - _graphOrigin.Y) * _nodeLayoutManager.Scale + _nodeLayoutManager.Offset.Y; _nodeLayoutManager.Offset = new PointF(mouseX, mouseY); } // check if we must keep the original position of _maintainNodePosition else if (_maintainNodePosition != null) { // move the graph so that _graphOrigin is at the same position in the view as it was before RectangleF bbox = _maintainNodePosition.IsFSM ? _maintainNodePosition.GetTotalBoundingBox() : _maintainNodePosition.BoundingBox; PointF viewpos = new PointF(bbox.X * _nodeLayoutManager.Scale, bbox.Y * _nodeLayoutManager.Scale); _nodeLayoutManager.Offset = new PointF(_graphOrigin.X - viewpos.X, _graphOrigin.Y - viewpos.Y); } // reset the node whose position we want to keep _maintainNodePosition = null; // draw the graph to the view _nodeLayoutManager.DrawGraph(e.Graphics, graphMousePos, _currentNode, SelectedNode, _highlightedNodeIds, _updatedNodeIds, _highlightedTransitionIds, _highlightBreakPoint, _profileInfos); // check if we are currently dragging a node and we must draw additional data if (_dragTargetNode != null && _dragAttachment == null && (KeyCtrlIsDown && _movedNode != null || _dragTargetNode.Node != _movedNode)) { if (_dragAttachMode == NodeAttachMode.Attachment) { // we could draw some stuff for attachements here } else { // draw the arrows for the attach modes // get the bounding box of the node RectangleF bbox = _dragTargetNode.BoundingBox; // get the bounding box of the connector _dragTargetConnector = null; // the depth of the area for the mouse const float offset = 12.0f; // the distance of the arrow from the border and its height const float innerOffset = 2.0f; // the horizintal middle of the node float centerX = bbox.Left + bbox.Width * 0.5f; float centerY = bbox.Top + bbox.Height * 0.5f; float centerBoxX = bbox.X + bbox.Width * 0.4f; float centerBoxWidth = bbox.Width * 0.2f; // the half width of the arrow depending of the node's height float arrowHalfWidth = (bbox.Height - innerOffset - innerOffset) * 0.5f; // calculate the mouse areas for the different attach modes RectangleF top = new RectangleF(centerBoxX, bbox.Top, centerBoxWidth, offset); RectangleF bottom = new RectangleF(centerBoxX, bbox.Bottom - offset, centerBoxWidth, offset); RectangleF center = new RectangleF(centerBoxX, centerY - offset * 0.5f, centerBoxWidth, offset); RectangleF left = new RectangleF(bbox.X, bbox.Y, offset, bbox.Height); // update for dragging in a new node BehaviorNode behavior = _dragNodeDefaults as BehaviorNode; if (behavior != null && behavior.FileManager == null) { behavior = null; } // the node that is currently dragged Node draggedNode = (_movedNode != null) ? _movedNode : (_dragNodeDefaults as Node); if (draggedNode == null) { return; } Node.Connector parentConnector = _dragTargetNode.Node.ParentConnector; bool canBeAdoptedByParent = parentConnector != null && (!parentConnector.IsAsChild || AdoptNodeByAncestor(_dragTargetNode.Node.Parent, draggedNode)); //bool targetCanBeAdoptedByParent = (_movedNode == null) || (_movedNode.ParentConnector != null) && _movedNode.ParentConnector.AcceptsChild(_dragTargetNode.Node); bool hasParentBehavior = _dragTargetNode.HasParentBehavior(behavior); bool parentHasParentBehavior = (_dragTargetNode.Parent == null); bool isFSM = _rootNodeView.IsFSM || (_rootNodeView.Children.Count == 0); bool mayTop = !isFSM && canBeAdoptedByParent /*&& targetCanBeAdoptedByParent*/ && !parentHasParentBehavior && parentConnector != null && parentConnector.AcceptsChild(draggedNode); bool mayBottom = mayTop; bool mayCenter = !parentHasParentBehavior && (_rootNodeView.IsFSM && draggedNode.IsFSM || canBeAdoptedByParent && draggedNode.GetType() != _dragTargetNode.Node.GetType() && parentConnector != null && !parentConnector.IsReadOnly && parentConnector.AcceptsChild(draggedNode, true) && draggedNode.CanAdoptChildren(_dragTargetNode.Node)); bool mayLeft = !isFSM && (_dragTargetNode.Node.Parent != _movedNode) && canBeAdoptedByParent && !parentHasParentBehavior && !hasParentBehavior && parentConnector != null && !parentConnector.IsReadOnly && parentConnector.AcceptsChild(draggedNode, true) && !(draggedNode is BehaviorNode) && draggedNode.CanAdoptNode(_dragTargetNode.Node); // update for moving an existing node bool dragTargetHasParentMovedNode = false; if (_movedNode != null) { mayCenter = false; dragTargetHasParentMovedNode = KeyShiftIsDown && _dragTargetNode.Node.HasParent(_movedNode); // a node may not dragged on itself and may not dragged on one of its own children if (_dragTargetNode.Node == _movedNode || dragTargetHasParentMovedNode) { //mayTop = KeyCtrlIsDown; mayTop &= KeyCtrlIsDown && (_dragTargetNode.Node.ParentConnector != null) && _dragTargetNode.Node.ParentConnector.AcceptsChild(_movedNode); mayBottom = mayTop; mayLeft = false; } else { // a dragged node cannot be placed in the same position again mayTop &= (KeyCtrlIsDown || _dragTargetNode.Node.PreviousNode != _movedNode); mayBottom &= (KeyCtrlIsDown || _dragTargetNode.Node.NextNode != _movedNode); mayLeft &= _movedNode.CanAdoptChildren(_dragTargetNode.Node) && (!KeyShiftIsDown || _movedNode.Children.Count == 0); } } if (_copiedNode != null) { mayCenter = false; mayLeft &= _copiedNode.CanAdoptChildren(_dragTargetNode.Node) && (!KeyShiftIsDown || _copiedNode.Children.Count == 0); mayTop &= (_dragTargetNode.Node.ParentConnector != null) && _dragTargetNode.Node.ParentConnector.AcceptsChild(_copiedNode); mayBottom = mayTop; } else if (_clipboardPasteMode) { mayCenter = false; mayLeft &= !KeyShiftIsDown; } // reset the attach mode _dragAttachMode = NodeAttachMode.None; // the vertices needed to draw the arrows PointF[] vertices = new PointF[3]; // draw the top arrow if this action is allowed if (mayTop) { vertices[0] = new PointF(centerX - arrowHalfWidth, top.Bottom - innerOffset); vertices[1] = new PointF(centerX, top.Top + innerOffset); vertices[2] = new PointF(centerX + arrowHalfWidth, top.Bottom - innerOffset); if (top.Contains(graphMousePos)) { _dragAttachMode = NodeAttachMode.Top; e.Graphics.FillPolygon(Brushes.White, vertices); } else { e.Graphics.FillPolygon(Brushes.Black, vertices); } } // draw the bottom arrow if this action is allowed if (mayBottom) { vertices[0] = new PointF(centerX - arrowHalfWidth, bottom.Top + innerOffset); vertices[1] = new PointF(centerX + arrowHalfWidth, bottom.Top + innerOffset); vertices[2] = new PointF(centerX, bottom.Bottom - innerOffset); if (_dragAttachMode == NodeAttachMode.None && bottom.Contains(graphMousePos)) { _dragAttachMode = NodeAttachMode.Bottom; e.Graphics.FillPolygon(Brushes.White, vertices); } else { e.Graphics.FillPolygon(Brushes.Black, vertices); } } // draw the center rectangle if this action is allowed if (mayCenter) { if (center.Contains(graphMousePos)) { _dragAttachMode = NodeAttachMode.Center; e.Graphics.FillRectangle(Brushes.White, centerX - arrowHalfWidth * 0.5f, centerY - innerOffset * 2.0f, arrowHalfWidth, innerOffset * 4.0f); } else { e.Graphics.FillRectangle(Brushes.Black, centerX - arrowHalfWidth * 0.5f, centerY - innerOffset * 2.0f, arrowHalfWidth, innerOffset * 4.0f); } } // draw the left arrow if this action is allowed if (mayLeft) { vertices[0] = new PointF(left.Right - innerOffset, left.Top + innerOffset); vertices[1] = new PointF(left.Right - innerOffset, left.Bottom - innerOffset); vertices[2] = new PointF(left.Left + innerOffset, left.Top + left.Height * 0.5f); if (_dragAttachMode == NodeAttachMode.None && left.Contains(graphMousePos)) { _dragAttachMode = NodeAttachMode.Left; e.Graphics.FillPolygon(Brushes.White, vertices); } else { e.Graphics.FillPolygon(Brushes.Black, vertices); } } // draw the right arrow if this action is allowed foreach(Node.Connector connector in _dragTargetNode.Connectors) { RectangleF bboxConnector = _dragTargetNode.GetConnectorBoundingBox(bbox, connector); RectangleF right = new RectangleF(bboxConnector.Right - offset, bboxConnector.Y, offset, bboxConnector.Height); bool mayRight = !_rootNodeView.IsFSM && !dragTargetHasParentMovedNode && !hasParentBehavior && !connector.IsReadOnly && connector.AcceptsChild(draggedNode) && (!connector.IsAsChild || AdoptNodeByAncestor(_dragTargetNode.Node, draggedNode)); if (mayRight && draggedNode != null && connector == draggedNode.ParentConnector) { mayRight = false; } if (mayRight) { float inOffset = bboxConnector.Height > innerOffset * 4.0f ? innerOffset : 3.0f; vertices[0] = new PointF(right.Left + inOffset, right.Top + inOffset); vertices[1] = new PointF(right.Right - inOffset, right.Top + right.Height * 0.5f); vertices[2] = new PointF(right.Left + inOffset, right.Bottom - inOffset); if (_dragAttachMode == NodeAttachMode.None && right.Contains(graphMousePos)) { _dragTargetConnector = _dragTargetNode.Node.GetConnector(connector.Identifier); _dragAttachMode = NodeAttachMode.Right; e.Graphics.FillPolygon(Brushes.White, vertices); } else { e.Graphics.FillPolygon(Brushes.Black, vertices); } } } } } // draw last mouse pos //e.Graphics.DrawRectangle(Pens.Red, graphMousePos.X -1.0f, graphMousePos.Y -1.0f, 2.0f, 2.0f); //when we are dragging an existing node we draw a small graph representing it if (_movedNodeGraph != null) { // update the layout for the graph. This happens only once inside the function. _movedNodeGraph.UpdateLayout(e.Graphics); // offset the graph to the mouse position _movedNodeGraph.Offset = new PointF(_nodeLayoutManager.Offset.X + graphMousePos.X * _nodeLayoutManager.Scale, _nodeLayoutManager.Offset.Y + graphMousePos.Y * _nodeLayoutManager.Scale - _movedNodeGraph.RootNodeLayout.LayoutRectangle.Height * 0.5f * _movedNodeGraph.Scale); // draw the graph _movedNodeGraph.DrawGraph(e.Graphics, graphMousePos); } // attachment if (_currentNode != null && _dragTargetNode != null && _dragAttachment != null && _dragTargetAttachment != null && _dragAttachment != _dragTargetAttachment && _dragTargetNode.Node.AcceptsAttachment(_dragAttachment.Attachment)) { _dragAttachMode = NodeAttachMode.None; Attachments.Attachment sourceAttach = _dragAttachment.SelectableObject as Attachments.Attachment; Attachments.Attachment targetAttach = _dragTargetAttachment.SelectableObject as Attachments.Attachment; if (sourceAttach != null && targetAttach != null && sourceAttach.IsPrecondition == targetAttach.IsPrecondition && sourceAttach.IsTransition == targetAttach.IsTransition && sourceAttach.IsEffector == targetAttach.IsEffector) { SubItemRegin regin = _dragTargetNode.GetSubItemRegin(graphMousePos); int itemIndex = _currentNode.GetSubItemIndex(_dragAttachment); int targetItemIndex = _dragTargetNode.GetSubItemIndex(_dragTargetAttachment); if (regin != SubItemRegin.Out && itemIndex >= 0 && targetItemIndex >= 0) { RectangleF bbox = _dragTargetNode.GetSubItemBoundingBox(graphMousePos); const float offset = 8.0f; const float innerOffset = 2.0f; float centerX = bbox.Left + bbox.Width * 0.5f; float centerY = bbox.Top + bbox.Height * 0.5f; float centerBoxX = bbox.X + bbox.Width * 0.4f; float arrowHalfWidth = bbox.Width * 0.12f; RectangleF top = new RectangleF(centerX - arrowHalfWidth, bbox.Top, arrowHalfWidth * 2.0f, offset); RectangleF bottom = new RectangleF(centerX - arrowHalfWidth, bbox.Bottom - offset, arrowHalfWidth * 2.0f, offset); PointF[] vertices = new PointF[3]; switch (regin) { case SubItemRegin.Top: if (KeyCtrlIsDown || _currentNode != _dragTargetNode || itemIndex != targetItemIndex - 1) { vertices[0] = new PointF(centerX - arrowHalfWidth, top.Bottom - innerOffset); vertices[1] = new PointF(centerX, top.Top + innerOffset); vertices[2] = new PointF(centerX + arrowHalfWidth, top.Bottom - innerOffset); if (top.Contains(graphMousePos)) { _dragAttachMode = NodeAttachMode.Top; e.Graphics.FillPolygon(Brushes.White, vertices); } else { e.Graphics.FillPolygon(Brushes.Black, vertices); } } break; case SubItemRegin.Bottom: if (KeyCtrlIsDown || _currentNode != _dragTargetNode || itemIndex != targetItemIndex + 1) { vertices[0] = new PointF(centerX - arrowHalfWidth, bottom.Top + innerOffset); vertices[1] = new PointF(centerX + arrowHalfWidth, bottom.Top + innerOffset); vertices[2] = new PointF(centerX, bottom.Bottom - innerOffset); if (bottom.Contains(graphMousePos)) { _dragAttachMode = NodeAttachMode.Bottom; e.Graphics.FillPolygon(Brushes.White, vertices); } else { e.Graphics.FillPolygon(Brushes.Black, vertices); } } break; } } } } if (_movedSubItem != null) { NodeViewData.SubItemText subitem = _movedSubItem as NodeViewData.SubItemText; if (subitem != null) { RectangleF boundingBox = new RectangleF(graphMousePos, new SizeF(50, 12)); e.Graphics.FillRectangle(subitem.BackgroundBrush, boundingBox); } } // draw FSM related DrawFSMArrow(e, graphMousePos); DrawFSMDragCurve(e, graphMousePos); //the first time of paint, to collapse plan failed branch by default Behavior b = this.RootNode as Behavior; if (b.PlanIsCollapseFailedBranch > 0) { if (b.PlanIsCollapseFailedBranch == Behavior.kPlanIsCollapseFailedBranch) { NodeViewData root = (NodeViewData)this.RootNodeView.Children[0]; CollapseFailedBrach(root); } b.PlanIsCollapseFailedBranch--; this.CenterNode(this._rootNodeView); this.LayoutChanged(); } }
private void DrawLocationType(Dictionary<LocationType, List<Location>> visible, LocationType typeToDraw, Bitmap imageToUse, Graphics drawOn, float zoom, float imageZoom) { List<Location> locs; List<Location> portalHubs; if ((typeToDraw & LocationType.AnyPortal) == 0 || !visible.TryGetValue(LocationType.PortalHub, out portalHubs)) { portalHubs = null; } if (visible.TryGetValue(typeToDraw, out locs)) { float zw = imageZoom * imageToUse.Width; float zh = imageZoom * imageToUse.Height; foreach (Location loc in locs) { PointF ptf = CoordsToPix(loc.Coords, zoom); RectangleF rectf = new RectangleF(ptf.X - zw / 2, ptf.Y - zh / 2, zw, zh); bool draw = true; // Hide portals that overlap a portal hub // (likely that the portal is part of the hub) if (portalHubs != null) { foreach (Location portalHub in portalHubs) { PointF portalHubPt = CoordsToPix(portalHub.Coords, zoom); if (rectf.Contains(portalHubPt)) { draw = false; break; } } } if (draw) { drawOn.DrawImage(loc.IsFavorite ? Icons.Map.Favorite : imageToUse, rectf); Rectangle rect = new Rectangle(Point.Truncate(rectf.Location), Size.Ceiling(rectf.Size)); mHotspots.AddFirst(new Hotspot(rect, loc)); } } } }
protected override void OnMouseDown(MouseEventArgs e) { if (!DesignMode) { var tabTextArea = (RectangleF)GetTabRect(SelectedIndex); tabTextArea = new RectangleF(tabTextArea.X + tabTextArea.Width - 22, 4, tabTextArea.Height - 3, tabTextArea.Height - 5); var pt = new Point(e.X, e.Y); if (tabTextArea.Contains(pt)) { //if (ConfirmOnClose) //{ // string tabPageText = this.TabPages[SelectedIndex].Text.TrimEnd(); // string message = string.Format("You are about to close {0} tab. Are you sure you want to continue?", tabPageText); // DialogResult dialogResult = MessageBox.Show(message, "Confirm close", MessageBoxButtons.YesNo); // if (dialogResult == DialogResult.No) // { // return; // } //} // Fire Event to Client if (OnClose != null) { OnClose(this, new CloseEventArgs(SelectedIndex)); } } if (CanDrawMenuButton(SelectedIndex)) { RectangleF tabMenuArea = GetTabRect(SelectedIndex); tabMenuArea = new RectangleF(tabMenuArea.X + tabMenuArea.Width - 43, 4, tabMenuArea.Height - 3, tabMenuArea.Height - 5); pt = new Point(e.X, e.Y); if (tabMenuArea.Contains(pt)) { if (((UnitTabPage)TabPages[SelectedIndex]).Menu != null) { ((UnitTabPage) TabPages[SelectedIndex]).Menu.Show(this, new Point((int)tabMenuArea.X, (int)(tabMenuArea.Y + tabMenuArea.Height))); } } } } }
public void Draw(Graphics g, PointF pntDrawOffset, Point pntMouseLocation, MouseButtons mbButtons, Dictionary<Kill, KillDisplayDetails> dicKills, List<BattlemapRoundChange> lstRounds, KillDisplayColours colours, Dictionary<int, Color> teamColours) { GraphicsPath gpTimelineOutline = new GraphicsPath(); gpTimelineOutline.AddLines(new Point[] { new Point(5, 0), new Point(0, 5), new Point(0, 15), new Point((int)g.ClipBounds.Width - 280, 15), new Point((int)g.ClipBounds.Width - 280, 5), new Point((int)g.ClipBounds.Width - 275, 0) }); //gpTimelineOutline.AddLine(new Point(this.m_mtsSeek.SeekerPosition, 15), new Point((int)g.ClipBounds.Width - 280, 15)); //gpTimelineOutline.AddLines(new Point[] { new Point(235, (int)g.ClipBounds.Height - 55), new Point(230, (int)g.ClipBounds.Height - 50), new Point(230, (int)g.ClipBounds.Height - 40), new Point((int)g.ClipBounds.Width - 50, (int)g.ClipBounds.Height - 40), new Point((int)g.ClipBounds.Width - 50, (int)g.ClipBounds.Height - 50), new Point((int)g.ClipBounds.Width - 45, (int)g.ClipBounds.Height - 55) }); gpTimelineOutline.Widen(this.m_pOneWidth); this.ObjectPath = gpTimelineOutline; RectangleF recBounds = gpTimelineOutline.GetBounds(); recBounds.Height += 50.0F; this.HotSpot = recBounds; //string strMouseOverKillList = String.Empty; float flMouseOffsetX = 0.0F; bool blRoundChanged = false; MapTextBlock timeList = new MapTextBlock(); foreach (BattlemapRoundChange RoundChange in new List<BattlemapRoundChange>(lstRounds)) { float flOffsetXs = (this.HotSpot.Width - 5.0F) - ((float)((DateTime.Now.Ticks - RoundChange.ChangeTime.Ticks) / TimeSpan.TicksPerSecond) / 3600.0F) * (this.HotSpot.Width - 5.0F); RectangleF recChangePosition = new RectangleF(flOffsetXs + this.m_pntDrawOffset.X - 2.0F, this.m_pntDrawOffset.Y, 4.0F, 20.0F); if (flOffsetXs >= 0.0F) { GraphicsPath gpChangeTime = new GraphicsPath(); gpChangeTime.AddLine(new PointF(flOffsetXs, 5), new PointF(flOffsetXs, 12)); gpChangeTime.Widen(this.m_pOneWidth); this.DrawBwShape(g, gpChangeTime, this.TimelineOpacity, 4.0F, Color.Black, Color.RoyalBlue); gpChangeTime.Dispose(); if (recChangePosition.Contains(new PointF(pntMouseLocation.X, pntMouseLocation.Y)) == true) { //strMouseOverKillList += String.Format("Round change {0}\r\n", RoundChange.Map.PublicLevelName); timeList.Strings.Add(new MapTextBlockString(String.Format("Round change {0}", RoundChange.Map.PublicLevelName), Color.Pink, true)); blRoundChanged = true; flMouseOffsetX = flOffsetXs; //flMouseOffsetX = flOffsetXs; } } } foreach (KeyValuePair<Kill, KillDisplayDetails> kvpKill in new Dictionary<Kill, KillDisplayDetails>(dicKills)) { float flOffsetXs = (this.HotSpot.Width - 5.0F) - ((float)((DateTime.Now.Ticks - kvpKill.Key.TimeOfDeath.Ticks) / TimeSpan.TicksPerSecond) / 3600.0F) * (this.HotSpot.Width - 5.0F); RectangleF recKillPosition = new RectangleF(flOffsetXs + this.m_pntDrawOffset.X - 2.0F, this.m_pntDrawOffset.Y, 4.0F, 20.0F); if (recKillPosition.Contains(new PointF(pntMouseLocation.X + 5.0F, pntMouseLocation.Y)) == true) { GraphicsPath gpKillTime = new GraphicsPath(); gpKillTime.AddLine(new PointF(flOffsetXs, 10), new PointF(flOffsetXs, 12)); gpKillTime.Widen(this.m_pOneWidth); this.DrawBwShape(g, gpKillTime, this.TimelineOpacity, 4.0F, Color.Black, Color.RoyalBlue); gpKillTime.Dispose(); Color killerColour = Color.White; Color victimColour = Color.White; if (colours == KillDisplayColours.EnemyColours) { killerColour = ControlPaint.Light(Color.SeaGreen); victimColour = ControlPaint.LightLight(Color.Black); } else if (colours == KillDisplayColours.TeamColours) { if (teamColours.ContainsKey(kvpKill.Key.Killer.TeamID) == true && teamColours.ContainsKey(kvpKill.Key.Victim.TeamID) == true) { killerColour = ControlPaint.Light(teamColours[kvpKill.Key.Killer.TeamID]); victimColour = ControlPaint.Light(teamColours[kvpKill.Key.Victim.TeamID]); } } if (kvpKill.Key.Killer.ClanTag.Length > 0) { timeList.Strings.Add(new MapTextBlockString(String.Format("[{0}] ", kvpKill.Key.Killer.ClanTag), killerColour, false)); } timeList.Strings.Add(new MapTextBlockString(kvpKill.Key.Killer.SoldierName, killerColour, false)); timeList.Strings.Add(new MapTextBlockString(String.Format("[{0}] ", kvpKill.Key.DamageType), Color.WhiteSmoke, false)); if (kvpKill.Key.Victim.ClanTag.Length > 0) { timeList.Strings.Add(new MapTextBlockString(String.Format("[{0}] ", kvpKill.Key.Victim.ClanTag), victimColour, false)); } timeList.Strings.Add(new MapTextBlockString(kvpKill.Key.Victim.SoldierName, victimColour, true)); flMouseOffsetX = flOffsetXs; } } if (timeList.Strings.Count > 0) { RectangleF recText = timeList.GetBounds(); PointF timeListOffset = new PointF(pntDrawOffset.X + flMouseOffsetX - recText.Width / 2.0F, pntDrawOffset.Y - recText.Height); if (timeListOffset.X + recText.Width > g.ClipBounds.Width) { timeListOffset.X = g.ClipBounds.Width - recText.Width; } timeList.Draw(g, timeListOffset, pntMouseLocation, mbButtons); } base.Draw(g, pntDrawOffset, pntMouseLocation, mbButtons); this.m_mtsSeek.ButtonOpacity = this.TimelineOpacity; this.m_mtsSeek.SeekerBounds = recBounds; this.m_mtsSeek.Draw(g, new PointF(pntDrawOffset.X, pntDrawOffset.Y + 13.0F), pntMouseLocation, mbButtons); timeList.Dispose(); }
protected override void OnMouseMove(MouseEventArgs e) { if (!DesignMode) { Graphics g = CreateGraphics(); g.SmoothingMode = SmoothingMode.AntiAlias; for (int i = 0; i < TabCount; i++) { var tabTextArea = (RectangleF)GetTabRect(i); tabTextArea = new RectangleF(tabTextArea.X + tabTextArea.Width - 22, 4, tabTextArea.Height - 3, tabTextArea.Height - 5); var pt = new Point(e.X, e.Y); if (tabTextArea.Contains(pt)) { using (var brush = new LinearGradientBrush(tabTextArea, SystemColors.Control, SystemColors.ControlLight, LinearGradientMode.Vertical)) { var colorBlend = new ColorBlend(3); colorBlend.Colors = new Color[] { Color.FromArgb(255, 252, 193, 183), Color.FromArgb(255, 252, 193, 183), Color.FromArgb(255, 210, 35, 2), Color.FromArgb(255, 210, 35, 2) }; colorBlend.Positions = new float[] { 0f, .4f, 0.5f, 1f }; brush.InterpolationColors = colorBlend; g.FillRectangle(brush, tabTextArea); g.DrawRectangle(Pens.White, tabTextArea.X + 2, 6, tabTextArea.Height - 3, tabTextArea.Height - 4); using (var pen = new Pen(Color.White, 2)) { g.DrawLine(pen, tabTextArea.X + 6, 9, tabTextArea.X + 15, 17); g.DrawLine(pen, tabTextArea.X + 6, 17, tabTextArea.X + 15, 9); } } } else { if (i != SelectedIndex) { using (var brush = new LinearGradientBrush(tabTextArea, SystemColors.Control, SystemColors.ControlLight, LinearGradientMode.Vertical)) { var colorBlend = new ColorBlend(3); colorBlend.Colors = new Color[] { SystemColors.ActiveBorder, SystemColors.ActiveBorder, SystemColors.ActiveBorder, SystemColors.ActiveBorder }; colorBlend.Positions = new float[] { 0f, .4f, 0.5f, 1f }; brush.InterpolationColors = colorBlend; g.FillRectangle(brush, tabTextArea); g.DrawRectangle(Pens.White, tabTextArea.X + 2, 6, tabTextArea.Height - 3, tabTextArea.Height - 4); using (var pen = new Pen(Color.White, 2)) { g.DrawLine(pen, tabTextArea.X + 6, 9, tabTextArea.X + 15, 17); g.DrawLine(pen, tabTextArea.X + 6, 17, tabTextArea.X + 15, 9); } } } } if (CanDrawMenuButton(i)) { var tabMenuArea = (RectangleF)GetTabRect(i); tabMenuArea = new RectangleF(tabMenuArea.X + tabMenuArea.Width - 43, 4, tabMenuArea.Height - 3, tabMenuArea.Height - 5); pt = new Point(e.X, e.Y); if (tabMenuArea.Contains(pt)) { using (var brush = new LinearGradientBrush(tabMenuArea, SystemColors.Control, SystemColors.ControlLight, LinearGradientMode.Vertical)) { var colorBlend = new ColorBlend(3); colorBlend.Colors = new Color[] { Color.FromArgb(255, 170, 213, 255), Color.FromArgb(255, 170, 213, 255), Color.FromArgb(255, 44, 157, 250), Color.FromArgb(255, 44, 157, 250) }; colorBlend.Positions = new float[] { 0f, .4f, 0.5f, 1f }; brush.InterpolationColors = colorBlend; g.FillRectangle(brush, tabMenuArea); g.DrawRectangle(Pens.White, tabMenuArea.X + 2, 6, tabMenuArea.Height - 2, tabMenuArea.Height - 4); using (var pen = new Pen(Color.White, 2)) { g.DrawLine(pen, tabMenuArea.X + 7, 11, tabMenuArea.X + 10, 16); g.DrawLine(pen, tabMenuArea.X + 10, 16, tabMenuArea.X + 13, 11); } } } else { if (i != SelectedIndex) { using (var brush = new LinearGradientBrush(tabMenuArea, SystemColors.Control, SystemColors.ControlLight, LinearGradientMode.Vertical)) { var colorBlend = new ColorBlend(3); colorBlend.Colors = new Color[] { SystemColors.ActiveBorder, SystemColors.ActiveBorder, SystemColors.ActiveBorder, SystemColors.ActiveBorder }; colorBlend.Positions = new float[] { 0f, .4f, 0.5f, 1f }; brush.InterpolationColors = colorBlend; g.FillRectangle(brush, tabMenuArea); g.DrawRectangle(Pens.White, tabMenuArea.X + 2, 6, tabMenuArea.Height - 2, tabMenuArea.Height - 4); using (var pen = new Pen(Color.White, 2)) { g.DrawLine(pen, tabMenuArea.X + 7, 11, tabMenuArea.X + 10, 16); g.DrawLine(pen, tabMenuArea.X + 10, 16, tabMenuArea.X + 13, 11); } } } } } } g.Dispose(); } }
public virtual bool HitTest(PointF pntTest) { System.Drawing.Drawing2D.Matrix mat = new System.Drawing.Drawing2D.Matrix(); mat.RotateAt(-RotationAngle, new PointF(X , Y )); PointF[] tempPoints = new PointF[1]; tempPoints[0].X = pntTest.X; tempPoints[0].Y = pntTest.Y; mat.TransformPoints( tempPoints); RectangleF rect = new RectangleF((X-(Width/2)), (Y-(Height/2)), Width, Height); if (rect.Contains(tempPoints[0])) { return true; } return false; }
public static List <CharBox> GetCharBoxsSurroundedByRectangle(List <CharBox> cbs, System.Drawing.RectangleF r) { return(cbs.Where(a => /*selectedR.IntersectsWith(a.R) || */ r.Contains(a.R)).ToList()); }