■ FrameworkElement 엘리먼트의 테두리 사각형을 구하는 방법을 보여준다.
※ sourceElement 객체의 테두리 사각형을 targetElement 객체를 기준으로 계산한다.
▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
using System; using System.Collections.Generic; using System.Linq; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Media; using Windows.Foundation; #region 테두리 사각형 구하기 - GetBoundingRectangle(sourceElement, targetElement) /// <summary> /// 테두리 사각형 구하기 /// </summary> /// <param name="sourceElement">소스 엘리먼트</param> /// <param name="targetElement">타겟 엘리먼트</param> /// <returns>테두리 사각형</returns> public Rect GetBoundingRectangle(this FrameworkElement sourceElement, FrameworkElement targetElement = null) { if(targetElement == null) { targetElement = Window.Current.Content as FrameworkElement; } if(targetElement == null) { throw new InvalidOperationException("Element not in visual tree."); } if(sourceElement == targetElement) { return new Rect(0, 0, targetElement.ActualWidth, targetElement.ActualHeight); } DependencyObject[] ancestorObjectElementArray = GetAncestorObjectEnumerable(sourceElement).ToArray(); if(!ancestorObjectElementArray.Contains(targetElement)) { throw new InvalidOperationException("Element not in visual tree."); } Point point1 = sourceElement.TransformToVisual(targetElement).TransformPoint(new Point()); Point point2 = sourceElement.TransformToVisual(targetElement).TransformPoint(new Point(sourceElement.ActualWidth, sourceElement.ActualHeight)); return new Rect(point1, point2); } #endregion #region 조상 객체 열거 가능형 구하기 - GetAncestorObjectEnumerable(sourceObject) /// <summary> /// 조상 객체 열거 가능형 구하기 /// </summary> /// <param name="sourceObject">소스 객체</param> /// <returns>조상 객체 열거 가능형</returns> private IEnumerable<DependencyObject> GetAncestorObjectEnumerable(DependencyObject sourceObject) { DependencyObject parentObject = VisualTreeHelper.GetParent(sourceObject); while(parentObject != null) { yield return parentObject; parentObject = VisualTreeHelper.GetParent(parentObject); } } #endregion |