【问题标题】:Get Elements position relative to screen in Xamarin在 Xamarin 中获取元素相对于屏幕的位置
【发布时间】:2016-10-06 09:36:23
【问题描述】:

我有一个带有上下文菜单的列表,当我单击时,选项列表(编辑、删除、信息)将显示在弹出窗口中。

这里我需要在上下文菜单图标的左下方显示这个弹出窗口,因为我需要上下文菜单相对于屏幕的位置。

谁能帮我在 Xamarin 中获取元素的 XY 位置?

提前致谢!

【问题讨论】:

    标签: c# xamarin position xamarin.forms


    【解决方案1】:

    这是我在Xamarin forums中找到的方法的版本:

    public static class ScreenCoords
    {
        /// <summary>
        /// A view's default X- and Y-coordinates are LOCAL with respect to the boundaries of its parent,
        /// and NOT with respect to the screen. This method calculates the SCREEN coordinates of a view.
        /// The coordinates returned refer to the top left corner of the view.
        /// </summary>
        public static Point GetScreenCoords(this VisualElement view)
        {
            var result = new Point(view.X, view.Y);
            while (view.Parent is VisualElement parent)
            {
                result = result.Offset(parent.X, parent.Y);
                view = parent;
            }
            return result;
        }
    

    【讨论】:

    • 这个方法在 iOS 上没有返回正确的坐标(我认为它忽略了安全区域),也许你知道解决这个问题的方法吗?
    • 它不会将相对或绝对返回到屏幕。它只将位置返回给父视图。所以如果你有一个scrollview或者stacklayout离开屏幕,它会返回到scrollview的绝对x、y坐标。屏幕上是可见的。
    • 我稍微清理了一下代码。另请注意,如果您使用NavigationPage,这将不包括导航栏的高度! (至少在Android上)似乎没有从 Xamarin Forms 获取导航栏高度的方法,因此获取实际屏幕坐标似乎需要a custom NavigationPageRenderer。哎呀。
    • 从头开始,我确实找到了一种获取导航栏高度的方法。见stackoverflow.com/a/66962482/238419
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 2011-06-27
    • 2015-04-08
    • 2019-11-14
    • 1970-01-01
    相关资源
    最近更新 更多