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

在开发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, 然后判断偏移位置。其实原理也比较简单,就不再赘述了,代码自取。

  

 

 

posted @ 2013-04-11 18:50  huangliangjie  阅读(315)  评论(0编辑  收藏  举报