1. 程式人生 > >UIWebview獲取網頁中所有圖片並加入點選事件,實現瀏覽圖片的效果

UIWebview獲取網頁中所有圖片並加入點選事件,實現瀏覽圖片的效果

- (void)webViewDidFinishLoad:(UIWebView *)aWebView {

//調整字號

NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '95%'";

    [_webViewstringByEvaluatingJavaScriptFromString:str];

//js方法遍歷圖片新增點選事件返回圖片個數

    static  NSString * const jsGetImages =

@"function getImages(){\

    var objs = document.getElementsByTagName(\"img\");\

    for(var i=0;i<objs.length;i++){\

    objs[i].onclick=function(){\

    document.location=\"myweb:imageClick:\"+this.src;\

    };\

    };\

    return objs.length;\

    };";

    [_webViewstringByEvaluatingJavaScriptFromString:jsGetImages];

//注入js方法

//注入自定義的js方法後別忘了呼叫否則不會生效(不呼叫也一樣生效了,,,不明白)

NSString *resurlt = [_webViewstringByEvaluatingJavaScriptFromString:@"getImages()"];

}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{

//url轉換為string

    NSString

 *requestString = [[request URLabsoluteString];

//hasPrefix 判斷建立的字串內容是否以pic:字元開始

    if ([requestString hasPrefix:@"myweb:imageClick:"]) {

        NSString *imageUrl = [requestString substringFromIndex:@"myweb:imageClick:".length];

self.navigationController.navigationBarHidden = YES;

        if (_bgView && [imageUrl isEqualToString:_imgUrl]) {

//設定不隱藏,還原放大縮小,顯示圖片

            _bgView.hidden = NO;

        }else if (_bgView){

            _bgView.hidden = NO;

            _webImage = nil;

            _webImgdata = nil;

            _indicatorView = nil;

            [self addImgWithUrl:imageUrl];

            _imgUrl = imageUrl;

        }else{

            [self showBigImage:imageUrl];//建立檢視並顯示圖片

            _imgUrl = imageUrl;

        }

        return NO;

    }

returnYES;

}

#pragma mark 顯示大圖片

-(void)showBigImage:(NSString *)imageUrl{

//建立灰色透明背景,使其背後內容不可操作

_bgView = [[UIViewallocinitWithFrame:CGRectMake(00SCREEN_WIDTHSCREEN_HEIGHT)];

    [_bgViewsetBackgroundColor:[UIColorblackColor]];

    [self.view addSubview:_bgView];

UITapGestureRecognizer *gesture = [[UITapGestureRecognizerallocinitWithTarget:selfaction:@selector(cancel)];

    [_bgViewaddGestureRecognizer:gesture];

_indicatorView = [[UIActivityIndicatorViewalloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];

    [_indicatorViewsetFrame:CGRectMake(self.view.centerXself.view.centerY5050)];

_indicatorView.hidesWhenStopped = YES;

    [_indicatorViewstartAnimating];

//建立顯示影象檢視

    _imgView = [[UIImageView allocinit];

_imgView.userInteractionEnabled = YES;

    [self addImgWithUrl:imageUrl];

    [_bgViewaddSubview:_imgView];

//新增捏合手勢

    [_imgViewaddGestureRecognizer:[[UIPinchGestureRecognizeralloc]initWithTarget:selfaction:@selector(handlePinch:)]];

    [_imgViewaddGestureRecognizer:[[UIPanGestureRecognizeralloc]initWithTarget:selfaction:@selector(handlePan:)]];

}

-(void)addImgWithUrl:(NSString *)imageUrl

{

dispatch_async(dispatch_get_main_queue(), ^{

        NSURL *url = [NSURL URLWithString:imageUrl];

_webImgdata = [NSDatadataWithContentsOfURL:url];

_webImage = [UIImageimageWithData:_webImgdata];

        [_indicatorViewstopAnimating];

        CGFloat imageH;

        CGFloat imageW;

        if (_webImage.size.height >= SCREEN_HEIGHT && _webImage.size.height > _webImage.size.width*1.5) {

            imageW = (SCREEN_HEIGHT*1.0)/_webImage.size.height * _webImage.size.width;

            [_imgView setSize:CGSizeMake(imageW, SCREEN_HEIGHT)];

        }else{

            imageH = (SCREEN_WIDTH*1.0)/_webImage.size.width * _webImage.size.height;

            [_imgView setSize:CGSizeMake(SCREEN_WIDTH, imageH)];

        }

        [_imgViewsetCenter:_bgView.center];

        [_imgViewsetImage:_webImage];

    });

}

-(void)cancel

{

self.navigationController.navigationBarHidden = NO;

    _bgView.hidden = YES;

}

//關閉按鈕

-(void)removeBigImage

{

    _bgView.hidden = YES;

}

- (void) handlePinch:(UIPinchGestureRecognizer*) recognizer

{

//縮放:設定縮放比例

    recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);

    recognizer.scale = 1;

}

- (void) handlePan:(UIPanGestureRecognizer*) recognizer

{

//檢視前置操作

    [recognizer.view.superview bringSubviewToFront:recognizer.view];

    CGPoint center = recognizer.view.center;

    CGFloat cornerRadius = recognizer.view.frame.size.width / 2;

    CGPoint translation = [recognizer translationInView:self.view];

//NSLog(@"%@", NSStringFromCGPoint(translation));

    recognizer.view.center = CGPointMake(center.x + translation.x, center.y + translation.y);

    [recognizer setTranslation:CGPointZero inView:self.view];

if (recognizer.state == UIGestureRecognizerStateEnded) {

//計算速度向量的長度,當他小於200時,滑行會很短

        CGPoint velocity = [recognizer velocityInView:self.view];

        CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));

        CGFloat slideMult = magnitude / 200;

//NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult); //e.g. 397.973175, slideMult: 1.989866

//基於速度和速度因素計算一個終點

        float slideFactor = 0.1 * slideMult;

        CGPoint finalPoint = CGPointMake(center.x + (velocity.x * slideFactor),

                                         center.y + (velocity.y * slideFactor));

//限制最小[cornerRadius]和最大邊界值[self.view.bounds.size.width - cornerRadius],以免拖動出螢幕界限

        finalPoint.x = MIN(MAX(finalPoint.x, cornerRadius),

                           self.view.bounds.size.width - cornerRadius);

        finalPoint.y = MIN(MAX(finalPoint.y, cornerRadius),

                           self.view.bounds.size.height - cornerRadius);

//使用 UIView 動畫使 view 滑行到終點

        [UIView animateWithDuration:slideFactor*2

                              delay:0

options:UIViewAnimationOptionCurveEaseOut

                         animations:^{

                             recognizer.view.center = CGPointMake(_bgView.centerX, center.y);

                         }

                         completion:nil];

    }

}

另附一個小問題:

在開發中使用uiwebview的時候會碰到在空間的四周出現一條黑線的問題。解決辦法如下

UIWebView *web=[[UIWebViewallocinit];

            web.opaque=NO;

            web.backgroundColor=[UIColorclearColor];