2010-05-17 61 views
2

当我使用WatiN进行测试时,我喜欢保存截图。有时我并不需要整个浏览器窗口的图片 - 我只想要一张我正在测试的元素的图片。下面WatiN NativeElement.GetElementBounds() - 什么是度量单位?

我试图保存的代码元素的图象产生了块框的图象,因为elementBounds.Top点的像素位置的方式经过屏幕的底部。 elementBounds.Width和.Height值也似乎大约是他们应该的一半。

这是一个华廷bug,或者是措施,我要转换为像素莫名其妙的不同单元,这些属性?

public static void SaveElementScreenshot 
    (WatiN.Core.IE ie, WatiN.Core.Element element, string screenshotPath) 
{ 
    ScrollIntoView(ie, element); 
    ie.BringToFront(); 

    var ieClass = (InternetExplorerClass) ie.InternetExplorer; 

    Rectangle elementBounds = element.NativeElement.GetElementBounds(); 
    int left = ieClass.Left + elementBounds.Left; 
    int top = ieClass.Top + elementBounds.Top; 
    int width = elementBounds.Width; 
    int height = elementBounds.Height; 

    using (var bitmap = new Bitmap(width, height)) 
    { 
     using (Graphics graphics = Graphics.FromImage(bitmap)) 
     { 
      graphics.CopyFromScreen 
       (new Point(left, top), Point.Empty, new Size(width, height)); 
     } 

     bitmap.Save(screenshotPath, ImageFormat.Jpeg); 
    } 
} 
+0

什么是ScrollIntoView?我无法找到它.. – Marco 2013-12-15 08:26:27

+0

马可,这篇博客文章包含了所有该类代码:http://geekswithblogs.net/brians/archive/2010/05/31/watin-screenshot-saver.aspx – 2013-12-18 18:47:22

回答

1

看起来像是一个WatiN错误。作为对WatiN issue tracker site讨论,为Internet Explorer元素“得到界限”的方法是这样的:

internal static Rectangle GetHtmlElementBounds(IHTMLElement element) 
{ 
    int offsetLeft = element.offsetLeft; 
    int offsetTop = element.offsetTop; 
    for (IHTMLElement element2 = element.parentElement; element2 != null; element2 = element2.parentElement) 
    { 
     offsetLeft += element2.offsetLeft; 
     offsetTop += element2.offsetTop; 
    } 
    int width = element.offsetWidth/2; 
    return new Rectangle(offsetLeft, offsetTop, width, element.offsetHeight/2); 
} 

的缺陷是,它划分offsetWidth和的offsetHeight由2

我更换了调用元素.NativeElement.GetElementBounds打电话给我自己“GetElementBounds”的方法,和它的作品我希望它的方式:

private static Rectangle GetElementBounds(Element element) 
{ 
    var ieElem = element.NativeElement as WatiN.Core.Native.InternetExplorer.IEElement; 
    IHTMLElement elem = ieElem.AsHtmlElement; 

    int left = elem.offsetLeft; 
    int top = elem.offsetTop; 

    for (IHTMLElement parent = elem.offsetParent; parent != null; parent = parent.offsetParent) 
    { 
     left += parent.offsetLeft; 
     top += parent.offsetTop; 
    } 

    return new Rectangle(left, top, elem.offsetWidth, elem.offsetHeight); 
} 

剩下的唯一问题是,顶部和左侧属性不补偿的大小浏览器窗口w的“chrome”,所以元素截图向下和向右移动比应该更远。

直到我弄清楚如何弥补这个,我采取的截图之前设置浏览器以“全屏”模式避免它。

相关问题