h5中的图片点击放大

潘楚
2023-12-01
在wkwebview的代理方法

//MARK: -- 加载完成

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation 中加入js代码

//js方法遍历图片添加点击事件 返回图片个数

     逻辑:

     1.遍历获取全部的图片;(只获取detail-main div下的图片,需要哪个下的图片就取哪个上的所有图片)

     2.生成一个Srting为所有图片的拼接,拼接时拿到所处数组下标;

     3.为图片添加点击事件,并添加数组所处下标

     注意点:

     1.如果仅仅拿到url而无下标的话,网页中如果有多张相同地址的图片 则会发生位置错乱

     2.声明时不要用 var yong let  不然方法添加的i 永远是length的值

     */

    static  NSString * const jsGetImages =

    @"function getImages(){\

    var objs = document.querySelectorAll(\".detail-main img\");\

    var imgScr = '';\

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

    imgScr = imgScr + objs[i].src +'LQXindex'+ i +'L+Q+X';\

    objs[i].οnclick=function(){\

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

    };\

    };\

    return imgScr;\

    };";

    [webView evaluateJavaScript:jsGetImages completionHandler:^(id _Nullable result, NSError * _Nullable error) {

        

    }];

    //注入自定义的js方法后别忘了调用 否则不会生效

    [webView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {

        NSString *urlResurlt = result;

        allUrlArray = [NSMutableArray arrayWithArray:[urlResurlt componentsSeparatedByString:@"L+Q+X"]];

        if (allUrlArray.count >= 2) {

            [allUrlArray removeLastObject];// 此时数组为每一个图片的url

        }

    }];

然后在wkwebview的代理方法

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler中处理

//hasPrefix 判断创建的字符串内容是否以pic:字符开始

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

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

        if (self.photoView) {

            //设置不隐藏,还原放大缩小,显示图片

            self.photoView.hidden = NO;

            self.photoView.alpha = 1.0;

            NSArray *imageIndex = [NSMutableArray arrayWithArray:[imageUrl componentsSeparatedByString:@"LQXindex"]];

            int i = [imageIndex.lastObject intValue];

            self.photoView.currentIndex = i;

        }else{

            [self showBigImage:imageUrl];//创建视图并显示图片

        }


#pragma mark 显示大图片

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

    //创建灰色透明背景,使其背后内容不可操作

    NSArray *imageIndex = [NSMutableArray arrayWithArray:[imageUrl componentsSeparatedByString:@"LQXindex"]];

    int i = [imageIndex.lastObject intValue];

    self.photoView = [[CCBigImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) images:allUrlArray imageIndex:i];

    self.photoView.backgroundColor = [UIColor blackColor];

    [self.view addSubview:self.photoView];

}


图片放大

.h

@interface CCBigImageView : CCBaseView


@property (nonatomic, assign) NSInteger currentIndex;


/**

 初始化


 @param frame frame

 @param imageArr 所有图片数组

 @param index 点击的图片的index

 @return CCBigImageView

 */

- (id)initWithFrame:(CGRect)frame images:(NSMutableArray *)imageArr imageIndex:(NSInteger)index;


-(void)hideView;


.m

@interface CCBigImageView()<UIScrollViewDelegate,UIGestureRecognizerDelegate>


{

    NSMutableArray *_imageArr;

    NSUInteger _count;

}


@property (nonatomic, strong) UIScrollView *imageScrollView;

@property (nonatomic, strong) UILabel *imageCountLab;


@end


@implementation CCBigImageView


- (id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        // Initialization code

        [self setupScrollView];

    }

    return self;

}


- (id)initWithFrame:(CGRect)frame images:(NSMutableArray *)imageArr imageIndex:(NSInteger)index

{

    _imageArr = imageArr;

    _count = _imageArr.count;


    self = [super initWithFrame:frame];

    if (self) {

        [self setupScrollView];

         self.currentIndex  = index;

    }

    return self;

}

-(void)hideView{

    [UIView animateWithDuration:0.2 animations:^{

        self.alpha = 0;

    } completion:^(BOOL finished) {

        for (UIScrollView *s in self.imageScrollView.subviews){

            if ([s isKindOfClass:[UIScrollView class]]){

                [s setZoomScale:1.0];

            }

        }

        self.hidden = YES;

    }];

}

-(void)setCurrentIndex:(NSInteger)currentIndex{

    _currentIndex = currentIndex;

    self.imageCountLab.text= [NSString stringWithFormat:@"%ld/%ld",_currentIndex+1,_count];

    self.imageScrollView.contentOffset = CGPointMake(currentIndex*SCREEN_WIDTH, 0);

    self.imageCountLab.text = [NSString stringWithFormat:@"%ld/%ld",currentIndex+1,_count];


}

- (void)setupScrollView

{

    self.imageScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,0,self.frame.size.width,self.frame.size.height-40)];

    self.imageScrollView.backgroundColor = [UIColor clearColor];

    self.imageScrollView.scrollEnabled =YES;

    self.imageScrollView.pagingEnabled =YES;

    self.imageScrollView.delegate =self;

    self.imageScrollView.contentSize =CGSizeMake(_count*SCREEN_WIDTH,self.frame.size.height-40);

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideView)];

    tap.delegate = self;

    [self.imageScrollView addGestureRecognizer:tap];

    for (int i =0; i <_count; i++){

        UITapGestureRecognizer *doubleTap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleDoubleTap:)];

        doubleTap.delegate = self;

        [doubleTap setNumberOfTapsRequired:2];

        

        UIScrollView *s = [[UIScrollView alloc]initWithFrame:CGRectMake(self.frame.size.width*i,0,self.frame.size.width, self.frame.size.height-40)];

        s.contentSize = CGSizeMake(self.frame.size.width, self.frame.size.height-40);

        s.backgroundColor = [UIColor clearColor];

        s.delegate =self;

        s.bouncesZoom = YES;

        s.minimumZoomScale = 1.0;

        s.maximumZoomScale = [self getTheScale];

        s.showsVerticalScrollIndicator = NO;

        s.showsHorizontalScrollIndicator  = NO;

        s.tag = i+1;

        [s setZoomScale:1.0];

        

        UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,SCREEN_WIDTH, 400)];

        imageview.backgroundColor = [UIColor clearColor];

        imageview.centerY = self.centerY;

        NSString *imageStr = [_imageArr objectAtIndex:i];

        NSString *imageURL = [[imageStr componentsSeparatedByString:@"LQXindex"] firstObject];

        [imageview sd_setImageWithURL:[NSURL URLWithString:imageURL] placeholderImage:[UIImage imageNamed:@""]];

        imageview.contentMode = UIViewContentModeScaleAspectFit;

        imageview.userInteractionEnabled =YES;

        imageview.tag = i+1;

        [imageview addGestureRecognizer:doubleTap];

        [s addSubview:imageview];

        [self.imageScrollView addSubview:s];

        [tap requireGestureRecognizerToFail:doubleTap];

    }

    self.imageCountLab = [[UILabel alloc] initWithFrame:CGRectMake(0,self.frame.size.height-40 , self.frame.size.width, 30)];

    self.imageCountLab.textAlignment = NSTextAlignmentCenter;

    self.imageCountLab.font = [UIFont systemFontOfSize:15];

    self.imageCountLab.textColor = [UIColor whiteColor];

    [self addSubview:self.imageCountLab];

    [self addSubview:self.imageScrollView];


}


#pragma mark - ScrollView delegate

-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{

    if (scrollView.tag >= 1) {

        for (UIView *v in scrollView.subviews){

            return v;

        }

    }

    

    return nil;

}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

{

    if(interfaceOrientation == UIInterfaceOrientationPortrait||interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)

    {

        return YES;

    }

    return NO;

}


-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

    

    if (scrollView == self.imageScrollView){

        CGFloat x = scrollView.contentOffset.x;

        if (x==-333){

            

        }

        else {

            for (UIScrollView *s in scrollView.subviews){

                if ([s isKindOfClass:[UIScrollView class]]){

                    [s setZoomScale:1.0]; //scrollView每滑动一次将要出现的图片较正常时候图片的倍数(将要出现的图片显示的倍数)

                }

            }

        }

    }

}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

    if (scrollView == self.imageScrollView){

        CGFloat x = scrollView.contentOffset.x;

        if (x==-333){

            

        }

        else {

            NSInteger index = x/self.frame.size.width;

            self.imageCountLab.text= [NSString stringWithFormat:@"%ld/%ld",index+1,_count];

        }

    }

}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {


    if (scrollView.tag >= 1) {

        for (UIView *enlargeImage in scrollView.subviews){

            CGSize boundsSize  = scrollView.bounds.size;

            CGSize contentSize = scrollView.contentSize;

            CGPoint imgCenter  = CGPointMake(contentSize.width / 2.0, contentSize.height / 2.0+CCNavBarHeight);

            

            if (contentSize.width < boundsSize.width) {

                imgCenter.x = boundsSize.width / 2.0;

            }

            

            if (contentSize.height < boundsSize.height) {

                imgCenter.y = boundsSize.height / 2.0;

            }

            

            enlargeImage.center = imgCenter;

            enlargeImage.contentMode = UIViewContentModeScaleAspectFit;


        }

    }


}


#pragma mark -

-(void)handleDoubleTap:(UIGestureRecognizer *)gesture{

    float scale = [self getTheScale];

    float newScale = [(UIScrollView*)gesture.view.superview zoomScale] * scale;//每次双击放大倍数

    if (newScale <= scale) {

        gesture.view.contentMode = UIViewContentModeScaleToFill;

        CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gesture locationInView:gesture.view]];

        [(UIScrollView*)gesture.view.superview zoomToRect:zoomRect animated:YES];

    }

    else{

        newScale = 1;

        gesture.view.contentMode = UIViewContentModeScaleAspectFit;

        [(UIScrollView*)gesture.view.superview setZoomScale:newScale animated:YES];

    }

}


- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center

{

    CGRect zoomRect;

    zoomRect.size.height = self.frame.size.height / scale;

    zoomRect.size.width  = self.frame.size.width  / scale;

    zoomRect.origin.x = center.x - (zoomRect.size.width  /2.0);

    zoomRect.origin.y = center.y - (zoomRect.size.height /2.0);

    return zoomRect;

}


- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{

    return YES;

}

-(float)getTheScale{

    float height = self.frame.size.height-40;

    return height/400.0;

}



 类似资料: