2012-01-15 93 views
0

因此,我有一個UIWebView,我在其中添加了一個觸摸手勢,並且我想要查找點擊的圖像的x,y原點座標Web視圖或如果可能的話在Web視圖中xy座標中的圖像中心。我的代碼是:如何在UIWebView中查找圖像的中心/ x,y座標

- (CGPoint) topLeftPointsForImage:(UIGestureRecognizer *)sender 
{ 
    CGPoint pt = [sender locationInView:self]; 
    NSString * offsetTop = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).offsetTop", pt.x, pt.y 
          ]; 

    NSString * offsetLeft = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).offsetLeft", pt.x, pt.y 
         ]; 

    NSString * scrollTop = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).parentNode.scrollTop", pt.x, pt.y 
           ]; 

    NSString * scrollLeft = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).parentNode.scrollLeft", pt.x, pt.y 
          ]; 


    float x = [[self stringByEvaluatingJavaScriptFromString:offsetTop] floatValue] - [[self stringByEvaluatingJavaScriptFromString:scrollTop] floatValue]; 
    float y = [[self stringByEvaluatingJavaScriptFromString:offsetLeft] floatValue] - [[self stringByEvaluatingJavaScriptFromString:scrollLeft] floatValue]; 
    NSLog(@"Coor height is %f with coor width is %f", x, y); 

    CGPoint point = CGPointMake(x, y); 
    return point; 
} 

然而,這似乎並沒有給我一個正確的值。我不是一個JavaScript大師,所以尋找一些建議。

+0

你收到什麼樣的價值?可能是這種情況,你需要將來自JS代碼的結果轉換爲字符串:document.elementFromPoint(%f,%f).offsetTop.toString() – 2012-01-15 17:30:01

回答

1

如果您在HTML頁面中使用jQuery,那麼你可以嘗試使用:

NSString * offsetTop = [NSString stringWithFormat:@"$(document).elementFromPoint(%f, %f).offsetTop;", pt.x, pt.y 
         ]; 

也在發言結束注意分號。所有的Javascript語句都必須有效並正確終止,就像在html頁面中一樣。

如果你注入庫,你必須正常投入使用命名空間功能類,如下所示:

"(function() {return "your data";})();" 
相關問題