1. 程式人生 > >h5中的圖片點選放大

h5中的圖片點選放大

在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的值

*/

staticNSString * 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].onclick=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 = [NSMutableArrayarrayWithArray:[urlResurlt componentsSeparatedByString:@"L+Q+X"]];

if (allUrlArray.count >= 2) {

[allUrlArrayremoveLastObject];// 此時陣列為每一個圖片的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 = [NSMutableArrayarrayWithArray:[imageUrl componentsSeparatedByString:@"LQXindex"]];

int i = [imageIndex.lastObject intValue];

self.photoView = [[CCBigImageViewalloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) images:allUrlArrayimageIndex:i];

self.photoView.backgroundColor = [UIColorblackColor];

[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

@interfaceCCBigImageView()<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

[selfsetupScrollView];

}

returnself;

}

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

{

_imageArr = imageArr;

_count = _imageArr.count;

self = [super initWithFrame:frame];

if (self) {

[selfsetupScrollView];

self.currentIndex= index;

}

returnself;

}

-(void)hideView{

[UIViewanimateWithDuration:0.2animations:^{

self.alpha = 0;

} completion:^(BOOL finished) {

for (UIScrollView *s inself.imageScrollView.subviews){

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

[s setZoomScale:1.0];

}

}

self.hidden = YES;

}];

}

-(void)setCurrentIndex:(NSInteger)currentIndex{

_currentIndex = currentIndex;

self.imageCountLab.text= [NSStringstringWithFormat:@"%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 = [[UIScrollViewalloc]initWithFrame:CGRectMake(0,0,self.frame.size.width,self.frame.size.height-40)];

self.imageScrollView.backgroundColor = [UIColorclearColor];

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 = [[UITapGestureRecognizeralloc] initWithTarget:selfaction:@selector(hideView)];

tap.delegate = self;

[self.imageScrollViewaddGestureRecognizer: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 = [[UIScrollViewalloc]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 = [UIColorclearColor];

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:[NSURLURLWithString:imageURL] placeholderImage:[UIImageimageNamed:@""]];

imageview.contentMode = UIViewContentModeScaleAspectFit;

imageview.userInteractionEnabled =YES;

imageview.tag = i+1;

[imageview addGestureRecognizer:doubleTap];

[s addSubview:imageview];

[self.imageScrollViewaddSubview:s];

[tap requireGestureRecognizerToFail:doubleTap];

}

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

self.imageCountLab.textAlignment = NSTextAlignmentCenter;

self.imageCountLab.font = [UIFontsystemFontOfSize:15];

self.imageCountLab.textColor = [UIColorwhiteColor];

[selfaddSubview:self.imageCountLab];

[selfaddSubview:self.imageScrollView];

}

#pragma mark - ScrollView delegate

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

if (scrollView.tag >= 1) {

for (UIView *v in scrollView.subviews){

return v;

}

}

returnnil;

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

{

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

{

return YES;

}

returnNO;

}

-(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{

returnYES;

}

-(float)getTheScale{

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

return height/400.0;

}