简体   繁体   中英

how do I find the position of an image in a UIWebView

I have a UIWebView in which it has a UITapGestureRecognizer and basically in my tap gesture recognizer I have:

- (CGPoint) pointsForImage:(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];

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

basically what I am trying to do is find the top left x and y position of the image. Not relative to the UIWebView but to the content view. So say that the position of the image is 1000 pixels down, but I am now currently browsing the UIWebView down half way and therefore the number I want to see is 200. I hope this makes sense

Actually UIWebView has a UIScrollView . You can access the UIScrollView in UIWebView using scrollView property. Then get the contentOffset of the scrollView . Finally, you got the contentOffset of the scrollView and the image position relative to the UIWebView , you can calculate the point you want.

Try this piece of Javascript:

stringByEvaluatingJavaScriptFromString below:

function getPosition(element){
    var el = element;
    var pos = [el.offsetLeft, el.offsetTop];
    var parent = el.offsetParent;
    if (parent != el) { 
      while (parent) {  
        pos[0] += parent.offsetLeft; 
        pos[1] += parent.offsetTop; 
        parent = parent.offsetParent;
      }
    }
    return pos;
}
getPosition(YourImageElement);

you'll get the image position returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM