UIWebView之获取所点位置图片URL

UIWebView有自己的UIResgure,如果我们手动加入自己的GestureRecognize将不能识别,如UILongPressGestureRecongnizer. 在浏览网页的时候,如果看到喜欢的图片,想把它保存下来如何办呢? 我们可以自己写一个程序来实现,用uiwebview开发一个自己的浏览器。

关面说到uiwebview不能识别long press gesture,幸好有一个可以识别,那就是double click.因此我们注册它,代码如下:

 

  1. UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];  
  2. doubleTap.numberOfTouchesRequired = 2;  
  3. [self.theWebView addGestureRecognizer:doubleTap];  

然后就是实现doubleTap:

 

  1. -(void) doubleTap :(UITapGestureRecognizer*) sender  
  2. {  
  3. //  <Find HTML tag which was clicked by user>  
  4. //  <If tag is IMG, then get image URL and start saving>  
  5.     int scrollPositionY = [[self.theWebView stringByEvaluatingJavaScriptFromString:@"window.pageYOffset"] intValue];  
  6.     int scrollPositionX = [[self.theWebView stringByEvaluatingJavaScriptFromString:@"window.pageXOffset"] intValue];  
  7.       
  8.     int displayWidth = [[self.theWebView stringByEvaluatingJavaScriptFromString:@"window.outerWidth"] intValue];  
  9.     CGFloat scale = theWebView.frame.size.width / displayWidth;  
  10.       
  11.     CGPoint pt = [sender locationInView:self.theWebView];  
  12.     pt.x *= scale;  
  13.     pt.y *= scale;  
  14.     pt.x += scrollPositionX;  
  15.     pt.y += scrollPositionY;  
  16.       
  17.     NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).tagName", pt.x, pt.y];  
  18.     NSString * tagName = [self.theWebView stringByEvaluatingJavaScriptFromString:js];  
  19.     if ([tagName isEqualToString:@"img"]) {  
  20.         NSString *imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", pt.x, pt.y];  
  21.         NSString *urlToSave = [self.theWebView stringByEvaluatingJavaScriptFromString:imgURL];  
  22.         NSLog(@"image url=%@", urlToSave);  
  23.     }  
  24. }  

这样我们就可以得到图片的url,然后下载保存就行了。
原文链接:http://blog.csdn.net/favormm/article/details/6614441

 

posted on 2012-11-16 17:36  无量少年  阅读(196)  评论(0编辑  收藏  举报

导航