检测元素是否在界面可显示区域

在开发windows phone应用程序的时候,可能会遇到如下的场景:

  • 一个列表(如Listbox)包含很多项。为了保证程序的性能,仅下载可视区域或者紧挨可视区一屏幕的图片。
  • 对列表的项做动画时,仅对可视区的项做动画,可以提升动画性能。

等等,这样的场景还有很多,上述只列出了两个比较常用的。但这些都有一个共同点--需要判断出屏幕可视区域的项,并针对这些项做处理。

 

下面的代码就足以满足这样的需求:

   /// <summary>
    /// Indicates whether the specified framework element
    /// is within the bounds of the application's root visual.
    /// </summary>
    /// <param name="element">The framework element.</param>
    /// <returns>
    /// True if the rectangular bounds of the framework element
    /// are completely outside the bounds of the application's root visual.
    /// </returns>
    private static bool IsOnScreen(FrameworkElement element)
    {
        PhoneApplicationFrame root = Application.Current.RootVisual as PhoneApplicationFrame;

        if (root == null)
        {
            return false;
        }

        GeneralTransform generalTransform;
        double height = root.ActualHeight;                

        try
        {
            generalTransform = element.TransformToVisual(root);
        }
        catch (ArgumentException)
        {
            return false;
        }
                
        Rect bounds = new Rect(
            generalTransform.Transform(new Point(0, 0)), 
            generalTransform.Transform(new Point(element.ActualWidth, element.ActualHeight)));

        return (bounds.Bottom > 0 && bounds.Top < height);
    }

 实际上这里利用了Transform, 然后判断偏移位置。其实原理也比较简单,就不再赘述了,代码自取。

  

 

 

转载于:https://www.cnblogs.com/navigator/archive/2013/04/11/2994899.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值