iOS選擇相冊(cè)圖片并展示

承接上一文吭产,這篇是選擇圖片的文章,具體代碼如下

有必要說一下的是isRemovePic是判斷當(dāng)前是否是刪除照片鸭轮;imageArray是用戶選擇的相片數(shù)組
值得一提的是臣淤,我采用了CTAssetsPickerController圖片選擇器,貌似這個(gè)作者現(xiàn)在不再維護(hù)這份代碼了窃爷,而也沒能在GitHub上找到更好的圖片選擇器邑蒋,所以各位同學(xué)如果有更好的圖片選擇器,請(qǐng)一定要告訴我噢按厘!

/** 加載照片*/
- (void)setImage {
    /** 如果是通過刪除照片的方法進(jìn)到加載照片就不添加加號(hào)圖片進(jìn)去*/
    if (!self.isRemovePic) {
        UIImage *addImage = [UIImage imageNamed:@"PicUpload_add"];
        [self.imageArray addObject:addImage];
    }
    
    self.isRemovePic = NO;
    
    for (NSInteger i = 0; i < [self.imageArray count]; i++) {
        CGFloat letterWidth = (SCREEN_WIDTH - 6 * LINKHOME_CUSTOM_DISTANCE_TEN) / 5;
        CGFloat imageViewX = i * (letterWidth + LINKHOME_CUSTOM_DISTANCE_TEN) + LINKHOME_CUSTOM_DISTANCE_TEN;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(imageViewX, 0, letterWidth, letterWidth)];
        imageView.userInteractionEnabled = YES;
        imageView.image = self.imageArray[i];
        imageView.tag = kImageTag + i;
        /** 因?yàn)樽詈笠粋€(gè)一定是添加的圖片医吊,所以給最后一個(gè)添加一個(gè)點(diǎn)擊添加手勢(shì)*/
        if (i == [self.imageArray count] - 1) {
            UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openPhoto)];
            [imageView addGestureRecognizer:tapGes];
        } else {    /** 為圖片添加一個(gè)右上角的刪除按鈕并且添加一個(gè)點(diǎn)擊顯示大圖的手勢(shì)*/
            UIButton *removeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            CGFloat removeX = letterWidth * 4 / 5;
            CGFloat removeW = letterWidth / 5;
            removeBtn.frame = CGRectMake(removeX, 0, removeW, removeW);
            [removeBtn setImage:[UIImage imageNamed:@"PicUpload_remove"] forState:UIControlStateNormal];
            [removeBtn addTarget:self action:@selector(removeImage:) forControlEvents:UIControlEventTouchUpInside];
            removeBtn.tag = i;
            [imageView addSubview:removeBtn];
            
            HLFeedBackImageTapGestureRecongnizer *tapGes = [[HLFeedBackImageTapGestureRecongnizer alloc] initWithTarget:self action:@selector(tapImage:)];
            tapGes.imageArray = self.imageArray;
            [imageView addGestureRecognizer:tapGes];
        }
        [self addSubview:imageView];
    }
}

/** 打開相冊(cè)*/
- (void)openPhoto {
    /** 判斷當(dāng)前授權(quán)狀態(tài)*/
    PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        switch (status) {
            case PHAuthorizationStatusRestricted:    /** 系統(tǒng)級(jí)別的控制(如家長(zhǎng)控制)*/
                break;
            case PHAuthorizationStatusDenied:    /** 用戶選擇了取消*/
                if (oldStatus != PHAuthorizationStatusNotDetermined) {
                    break;
                }
                break;
            case PHAuthorizationStatusAuthorized:    /** 當(dāng)前用戶允許app訪問相冊(cè)*/
                [self choosePhotos];
            default:
                break;
        }
     }];
}

/** 選擇圖片*/
- (void)choosePhotos {
    dispatch_async(dispatch_get_main_queue(), ^{
        CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
        
        picker.showsSelectionIndex = YES;
        
        picker.delegate = self;
        
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            picker.modalPresentationStyle = UIModalPresentationFormSheet;
        }
        
        UIWindow *window = [[UIApplication sharedApplication] keyWindow];
        [window.rootViewController presentViewController:picker animated:YES completion:nil];
    });
}

/** 重新加載照片*/
- (void)reload {
    /** 首先把當(dāng)前顯示的所有控件都移除*/
    for (UIView *view in [self subviews]) {
        [view removeFromSuperview];
    }
    
    /** 再將數(shù)組中的圖片重新排列出來*/
    [self setImage];
}

/** 移除某一張照片*/
- (void)removeImage:(UIButton *)button {
    self.isRemovePic = YES;
    [self.imageArray removeObjectAtIndex:button.tag];
    [self reload];
}

/** 點(diǎn)擊圖片的手勢(shì)*/
- (void)tapImage:(HLFeedBackImageTapGestureRecongnizer *)tapGes{
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    UIView *maskview = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    maskview.backgroundColor = [UIColor blackColor];
    [window addSubview:maskview];
    
    HLFeedBackShowImageView *fbImageV = [[HLFeedBackShowImageView alloc] initWithFrame:[UIScreen mainScreen].bounds byClick:tapGes.view.tag appendArray:tapGes.imageArray];
    [fbImageV show:maskview didFinish:^(){
        [UIView animateWithDuration:0.5f animations:^{
            fbImageV.alpha = 0.0f;
            maskview.alpha = 0.0f;
        } completion:^(BOOL finished) {
            [fbImageV removeFromSuperview];
            [maskview removeFromSuperview];
        }];
        
    }];
}

#pragma mark - CTAssetsPickerControllerDelegate
/** 選擇完成時(shí)會(huì)調(diào)用*/
- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray<PHAsset *> *)assets {
    /** 關(guān)閉圖片選擇控制器*/
    [picker dismissViewControllerAnimated:YES completion:^{
        CGFloat scale = [UIScreen mainScreen].scale;
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        options.resizeMode = PHImageRequestOptionsResizeModeExact;
        options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
        
        /** 遍歷選擇的所有圖片*/
        for (NSInteger i = 0; i < assets.count; i++) {
            PHAsset *asset = assets[i];
            CGSize size = CGSizeMake(asset.pixelWidth / scale, asset.pixelHeight / scale);
    
            /** 獲取圖片*/
            [[PHImageManager defaultManager] requestImageForAsset:asset
                                                       targetSize:size
                                                      contentMode:PHImageContentModeDefault
                                                          options:options
                                                    resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                                                        [self.imageArray removeLastObject];
                                                        [self.imageArray addObject:result];
                                                        /** 刷新*/
                                                        [self reload];
            }];
        }
    }];
}

/** 相片的最大選擇數(shù)方法*/
- (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset {
    NSInteger max = 5;
    if (picker.selectedAssets.count + self.imageArray.count - 1 >= max) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:LocatizedStirngForkey(@"notice") message:LocatizedStirngForkey(@"feedback_more_photo") preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:LocatizedStirngForkey(@"dialog_OK") style:UIAlertActionStyleDefault handler:nil]];
        
        [picker presentViewController:alert animated:YES completion:nil];
        
        return NO;
    }
    return YES;
}

下面的是,在頁(yè)面上展示出選擇圖片后逮京,點(diǎn)擊圖片能夠顯示大圖并且能夠放大縮小滑動(dòng)等:
.h:

typedef  void(^didRemoveImage)(void);

@interface HLFeedBackShowImageView : UIView<UIScrollViewDelegate>
{
    UIImageView *showImage;
}
@property (nonatomic,copy) didRemoveImage removeImg;

- (void)show:(UIView *)bgView didFinish:(didRemoveImage)tempBlock;

- (id)initWithFrame:(CGRect)frame byClick:(NSInteger)clickTag appendArray:(NSArray *)appendArray;

.m:

#define kImageTag 9999

@implementation HLFeedBackShowImageView
{
    UIScrollView *_scrollView;
    CGRect self_Frame;
    NSInteger page;
    BOOL doubleClick;
}

- (id)initWithFrame:(CGRect)frame byClick:(NSInteger)clickTag appendArray:(NSArray *)appendArray {
    if ([super initWithFrame:frame]) {
        
        self_Frame = frame;

        self.alpha = 0.0f;
        page = 0;
        doubleClick = YES;
        
        NSMutableArray *array = [NSMutableArray arrayWithArray:appendArray];
        [array removeLastObject];
        
        [self configScrollViewWith:clickTag andAppendArray:array];
        
        UITapGestureRecognizer *tapGser = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(disappear)];
        tapGser.numberOfTouchesRequired = 1;
        tapGser.numberOfTapsRequired = 1;
        [self addGestureRecognizer:tapGser];
        
        UITapGestureRecognizer *doubleTapGser = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeBig:)];
        doubleTapGser.numberOfTapsRequired = 2;
        [self addGestureRecognizer:doubleTapGser];
        [tapGser requireGestureRecognizerToFail:doubleTapGser];
    }
    
    return self;
}

- (void)configScrollViewWith:(NSInteger)clickTag andAppendArray:(NSArray *)appendArray {
    _scrollView = [[UIScrollView alloc] initWithFrame:self_Frame];
    _scrollView.backgroundColor = [UIColor blackColor];
    _scrollView.pagingEnabled = true;
    _scrollView.delegate = self;
    _scrollView.contentSize = CGSizeMake(self.frame.size.width * appendArray.count, 0);
    [self addSubview:_scrollView];
    
    float W = self.frame.size.width;
    
    for (int i = 0; i < appendArray.count; i ++) {
        UIScrollView *imageScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(self.frame.size.width * i, 0, self.frame.size.width, self.frame.size.height)];
        imageScrollView.backgroundColor = [UIColor blackColor];
        imageScrollView.contentSize = CGSizeMake(self.frame.size.width, self.frame.size.height);
        imageScrollView.delegate = self;
        imageScrollView.maximumZoomScale = 4;
        imageScrollView.minimumZoomScale = 1;
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.bounds];
        UIImage *img = [appendArray objectAtIndex:i];
        imageView.image = img;
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        [imageScrollView addSubview:imageView];
        [_scrollView addSubview:imageScrollView];
        
        imageScrollView.tag = 100 + i ;
        imageView.tag = 1000 + i;
    
    }
    
    [_scrollView setContentOffset:CGPointMake(W * (clickTag - kImageTag), 0) animated:YES];
    page = clickTag - kImageTag;
}

- (void)disappear {
    
    _removeImg();
    
}

- (void)changeBig:(UITapGestureRecognizer *)tapGes {
    CGFloat newscale = 1.9;
    UIScrollView *currentScrollView = (UIScrollView *)[self viewWithTag:page + 100];
    CGRect zoomRect = [self zoomRectForScale:newscale withCenter:[tapGes locationInView:tapGes.view] andScrollView:currentScrollView];
    
    if (doubleClick == YES)  {
        [currentScrollView zoomToRect:zoomRect animated:YES];
    }else {
        [currentScrollView zoomToRect:currentScrollView.frame animated:YES];
    }
    
    doubleClick = !doubleClick;
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    UIImageView *imageView = (UIImageView *)[self viewWithTag:scrollView.tag + 900];
    
    return imageView;
}

- (CGRect)zoomRectForScale:(CGFloat)newscale withCenter:(CGPoint)center andScrollView:(UIScrollView *)scrollV {
    CGRect zoomRect = CGRectZero;
    
    zoomRect.size.height = scrollV.frame.size.height / newscale;
    zoomRect.size.width = scrollV.frame.size.width  / newscale;
    zoomRect.origin.x = center.x - (zoomRect.size.width  / 2.0);
    zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0);

    return zoomRect;
}

- (void)show:(UIView *)bgView didFinish:(didRemoveImage)tempBlock {
    [bgView addSubview:self];
    
    _removeImg = tempBlock;
    
    [UIView animateWithDuration:.4f animations:^{
        self.alpha = 1.0f;
    }];
}


#pragma mark - ScorllViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGPoint offset = _scrollView.contentOffset;
    page = offset.x / self.frame.size.width ;
    
    UIScrollView *scrollV_next = (UIScrollView *)[self viewWithTag:page + 100 + 1];    /** 前一頁(yè)*/
    
    if (scrollV_next.zoomScale != 1.0){
        scrollV_next.zoomScale = 1.0;
    }
    
    UIScrollView *scollV_pre = (UIScrollView *)[self viewWithTag:page + 100 - 1];    /** 后一頁(yè)*/
    if (scollV_pre.zoomScale != 1.0){
        scollV_pre.zoomScale = 1.0;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末卿堂,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子懒棉,更是在濱河造成了極大的恐慌草描,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,682評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件策严,死亡現(xiàn)場(chǎng)離奇詭異穗慕,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)享钞,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,277評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門揍诽,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人栗竖,你說我怎么就攤上這事暑脆。” “怎么了狐肢?”我有些...
    開封第一講書人閱讀 165,083評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵添吗,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我份名,道長(zhǎng)碟联,這世上最難降的妖魔是什么妓美? 我笑而不...
    開封第一講書人閱讀 58,763評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮鲤孵,結(jié)果婚禮上壶栋,老公的妹妹穿的比我還像新娘。我一直安慰自己普监,他們只是感情好贵试,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,785評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著凯正,像睡著了一般毙玻。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上廊散,一...
    開封第一講書人閱讀 51,624評(píng)論 1 305
  • 那天桑滩,我揣著相機(jī)與錄音,去河邊找鬼允睹。 笑死运准,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的擂找。 我是一名探鬼主播戳吝,決...
    沈念sama閱讀 40,358評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼贯涎!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起慢洋,我...
    開封第一講書人閱讀 39,261評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤塘雳,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后普筹,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體败明,經(jīng)...
    沈念sama閱讀 45,722評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評(píng)論 3 336
  • 正文 我和宋清朗相戀三年太防,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了妻顶。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,030評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡蜒车,死狀恐怖讳嘱,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情酿愧,我是刑警寧澤沥潭,帶...
    沈念sama閱讀 35,737評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站嬉挡,受9級(jí)特大地震影響钝鸽,放射性物質(zhì)發(fā)生泄漏汇恤。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,360評(píng)論 3 330
  • 文/蒙蒙 一拔恰、第九天 我趴在偏房一處隱蔽的房頂上張望因谎。 院中可真熱鬧,春花似錦颜懊、人聲如沸蓝角。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,941評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽使鹅。三九已至,卻和暖如春昌抠,著一層夾襖步出監(jiān)牢的瞬間患朱,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,057評(píng)論 1 270
  • 我被黑心中介騙來泰國(guó)打工炊苫, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留裁厅,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,237評(píng)論 3 371
  • 正文 我出身青樓侨艾,卻偏偏與公主長(zhǎng)得像执虹,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子唠梨,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,976評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容