UIWebView长按图片生成保存菜单

转载自:  http://zl4393753.iteye.com/blog/1752135

UIWebView长按图片生成保存菜单 
参考: 
http://www.icab.de/blog/2010/07/11/customize-the-contextual-menu-of-uiwebview/ 
http://www.icab.de/blog/2011/10/17/elementfrompoint-under-ios-5/comment-page-1/#comment-30184 

自定义UILongPressGestureRecognizer 
创建 UnpreventableUILongPressGestureRecognizer.h 

C代码   收藏代码
  1. #import   
  2. @interface UnpreventableUILongPressGestureRecognizer : UILongPressGestureRecognizer {  
  3. }  
  4. @end  


UnpreventableUILongPressGestureRecognizer.m 
C代码   收藏代码
  1. #import "UnpreventableUILongPressGestureRecognizer.h"  
  2.    
  3. @implementation UnpreventableUILongPressGestureRecognizer  
  4. - (BOOL)canBePreventedByGestureRecognizer:(UIGestureRecognizer *)preventedGestureRecognizer {  
  5.     return NO;  
  6. }  
  7. @end  


UIWebview页面给webview添加手势 ViewController.m: 
C代码   收藏代码
  1. UnpreventableUILongPressGestureRecognizer *longPressRecognizer = [[UnpreventableUILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];  
  2. longPressRecognizer.allowableMovement = 20;  
  3. longPressRecognizer.minimumPressDuration = 1.0f;  
  4. [webview addGestureRecognizer:longPressRecognizer];  


ViewController.m 处理手势: 
C代码   收藏代码
  1. -(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer  
  2. {  
  3.     if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {  
  4.            
  5.         CGPoint pt = [gestureRecognizer locationInView:self.webview];  
  6.            
  7.         // convert point from view to HTML coordinate system  
  8.         // 뷰의 포인트 위치를 HTML 좌표계로 변경한다.  
  9.         CGSize viewSize = [webview frame].size;  
  10.         CGSize windowSize = [webview windowSize];  
  11.         CGFloat f = windowSize.width / viewSize.width;  
  12.    
  13.         if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 5.0) {  
  14.             pt.x = pt.x * f;  
  15.             pt.y = pt.y * f;  
  16.         } else {  
  17.             // On iOS 4 and previous, document.elementFromPoint is not taking  
  18.             // offset into account, we have to handle it  
  19.             CGPoint offset = [webview scrollOffset];  
  20.             pt.x = pt.x * f + offset.x;  
  21.             pt.y = pt.y * f + offset.y;  
  22.         }  
  23.            
  24.         [self openContextualMenuAt:pt];  
  25.     }  
  26. }  


创建分类 WebViewAdditions.h 
C代码   收藏代码
  1. #import   
  2. @interface UIWebView(WebViewAdditions)  
  3. - (CGSize)windowSize;  
  4. - (CGPoint)scrollOffset;  
  5. @end  
  6.   


WebViewAdditions.m 
C代码   收藏代码
  1. #import "WebViewAdditions.h"  
  2.    
  3. @implementation UIWebView(WebViewAdditions)  
  4.    
  5. - (CGSize)windowSize  
  6. {  
  7.     CGSize size;  
  8.     size.width = [[self stringByEvaluatingJavaScriptFromString:@"window.innerWidth"] integerValue];  
  9.     size.height = [[self stringByEvaluatingJavaScriptFromString:@"window.innerHeight"] integerValue];  
  10.     return size;  
  11. }  
  12.    
  13. - (CGPoint)scrollOffset  
  14. {  
  15.     CGPoint pt;  
  16.     pt.x = [[self stringByEvaluatingJavaScriptFromString:@"window.pageXOffset"] integerValue];  
  17.     pt.y = [[self stringByEvaluatingJavaScriptFromString:@"window.pageYOffset"] integerValue];  
  18.     return pt;  
  19. }  
  20. @end  


弹出菜单 ViewController.m 
C代码   收藏代码
  1. - (void)openContextualMenuAt:(CGPoint)pt{  
  2.     // Load the JavaScript code from the Resources and inject it into the web page  
  3.     NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"Naving" ofType:@"bundle"]];  
  4.     NSString *path = [bundle pathForResource:@"JSTools" ofType:@"js"];  
  5.     NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];  
  6.     [webview stringByEvaluatingJavaScriptFromString:jsCode];  
  7.        
  8.     // get the Tags at the touch location  
  9.     NSString *tags = [webview stringByEvaluatingJavaScriptFromString:  
  10.                       [NSString stringWithFormat:@"MyAppGetHTMLElementsAtPoint(%i,%i);",(NSInteger)pt.x,(NSInteger)pt.y]];  
  11.        
  12.     NSString *tagsHREF = [webview stringByEvaluatingJavaScriptFromString:  
  13.                           [NSString stringWithFormat:@"MyAppGetLinkHREFAtPoint(%i,%i);",(NSInteger)pt.x,(NSInteger)pt.y]];  
  14.        
  15.     NSString *tagsSRC = [webview stringByEvaluatingJavaScriptFromString:  
  16.                          [NSString stringWithFormat:@"MyAppGetLinkSRCAtPoint(%i,%i);",(NSInteger)pt.x,(NSInteger)pt.y]];  
  17.        
  18.     NSLog(@"tags : %@",tags);  
  19.     NSLog(@"href : %@",tagsHREF);  
  20.     NSLog(@"src : %@",tagsSRC);  
  21.        
  22.     if (!_actionActionSheet) {  
  23.         _actionActionSheet = nil;  
  24.     }  
  25.     _actionActionSheet = [[UIActionSheet alloc] initWithTitle:nil  
  26.                                                        delegate:self  
  27.                                               cancelButtonTitle:nil  
  28.                                          destructiveButtonTitle:nil  
  29.                                               otherButtonTitles:nil];  
  30.        
  31.     selectedLinkURL = @"";  
  32.     selectedImageURL = @"";  
  33.        
  34.     // If an image was touched, add image-related buttons.  
  35.     if ([tags rangeOfString:@",IMG,"].location != NSNotFound) {  
  36.         selectedImageURL = tagsSRC;  
  37.            
  38.         if (_actionActionSheet.title == nil) {  
  39.             _actionActionSheet.title = tagsSRC;  
  40.         }  
  41.            
  42.         [_actionActionSheet addButtonWithTitle:@"Save Image"];  
  43.         [_actionActionSheet addButtonWithTitle:@"Copy Image"];  
  44.     }  
  45.     // If a link is pressed add image buttons.  
  46.     if ([tags rangeOfString:@",A,"].location != NSNotFound){  
  47.         selectedLinkURL = tagsHREF;  
  48.            
  49.         _actionActionSheet.title = tagsHREF;  
  50.         [_actionActionSheet addButtonWithTitle:@"Open Link"];  
  51.         [_actionActionSheet addButtonWithTitle:@"Copy Link"];  
  52.     }  
  53.        
  54.     if (_actionActionSheet.numberOfButtons > 0) {  
  55.         [_actionActionSheet addButtonWithTitle:@"Cancel"];  
  56.         _actionActionSheet.cancelButtonIndex = (_actionActionSheet.numberOfButtons-1);  
  57.            
  58.            
  59.         [_actionActionSheet showInView:webview];  
  60.     }  
  61.        
  62. }  


工具文件 JSTools.js 
Js代码   收藏代码
  1. function MyAppGetHTMLElementsAtPoint(x,y) {  
  2.     var tags = ",";  
  3.     var e = document.elementFromPoint(x,y);  
  4.     while (e) {  
  5.         if (e.tagName) {  
  6.             tags += e.tagName + ',';  
  7.         }  
  8.         e = e.parentNode;  
  9.     }  
  10.     return tags;  
  11. }  
  12.    
  13. function MyAppGetLinkSRCAtPoint(x,y) {  
  14.     var tags = "";  
  15.     var e = document.elementFromPoint(x,y);  
  16.     while (e) {  
  17.         if (e.src) {  
  18.             tags += e.src;  
  19.             break;  
  20.         }  
  21.         e = e.parentNode;  
  22.     }  
  23.     return tags;  
  24. }  
  25.    
  26. function MyAppGetLinkHREFAtPoint(x,y) {  
  27.     var tags = "";  
  28.     var e = document.elementFromPoint(x,y);  
  29.     while (e) {  
  30.         if (e.href) {  
  31.             tags += e.href;  
  32.             break;  
  33.         }  
  34.         e = e.parentNode;  
  35.     }  
  36.     return tags;  
  37. }  


ViewController.m 处理ActionSheet事件 
C代码   收藏代码
  1. #pragma UIActionSheetDelegate  
  2. -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{  
  3.     if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"Open Link"]){  
  4.         [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:selectedLinkURL]]];  
  5.     }  
  6.     else if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"Copy Link"]){  
  7.         [[UIPasteboard generalPasteboard] setString:selectedLinkURL];  
  8.     }  
  9.     else if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"Copy Image"]){  
  10.         [[UIPasteboard generalPasteboard] setString:selectedImageURL];  
  11.     }  
  12.     else if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"Save Image"]){  
  13.         NSOperationQueue *queue = [NSOperationQueue new];  
  14.         NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self  
  15.                                                                                 selector:@selector(saveImageURL:) object:selectedImageURL];  
  16.         [queue addOperation:operation];  
  17.         //[operation release];  
  18.     }  
  19. }  
  20.    
  21. -(void)saveImageURL:(NSString*)url{  
  22.     [self performSelectorOnMainThread:@selector(showStartSaveAlert)   
  23.                            withObject:nil  
  24.                         waitUntilDone:YES];  
  25.        
  26.     UIImageWriteToSavedPhotosAlbum([UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]], nil, nil, nil);  
  27.        
  28.     [self performSelectorOnMainThread:@selector(showFinishedSaveAlert)  
  29.                            withObject:nil  
  30.                         waitUntilDone:YES];  
  31. }  

你可能感兴趣的:(UIWebView长按图片生成保存菜单)