MLSelectPhoto类似微信多选图片

先看下效果展示:
这里写图片描述
这个是基于MLSelectPhoto做了一点的修改
demo地址:https://github.com/tuwanli/MutplyPhotos
主要代码:

#import "ViewController.h"
#import "MLSelectPhotoPickerViewController.h"
#import "MLSelectPhotoAssets.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "UIImage+MyResize.h"

#import <AssetsLibrary/ALAsset.h>

#import <AssetsLibrary/ALAssetsLibrary.h>

#import <AssetsLibrary/ALAssetsGroup.h>

#import <AssetsLibrary/ALAssetRepresentation.h>

#define p_w (self.view.frame.size.width-5*20)/4
@interface ViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *photoArr;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib
    _photoArr = [[NSMutableArray alloc]init];
    [self.view addSubview:self.tableView];
}

- (UITableView *)tableView
{

    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, _clickBtn.frame.origin.y+_clickBtn.frame.size.height, self.view.frame.size.width, self.view.frame.size.height-30-_clickBtn.frame.size.height) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
- (IBAction)clickAction {
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"选择照片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从相册中选择", nil];
    [sheet showInView:self.view];
}
#pragma mark--选取相册图片
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {

        [self selectFromCamera];
    }
    if (buttonIndex == 1) {
        MLSelectPhotoPickerViewController *selectVC = [[MLSelectPhotoPickerViewController alloc]init];
        selectVC.status = PickerViewShowStatusCameraRoll;
        selectVC.maxCount = 4;
        [selectVC showPickerVc:self];
        selectVC.callBack = ^(NSArray *assets){

            [assets enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                MLSelectPhotoAssets *tempAsset = obj;
                //缩略图
                UIImage *thumbImage  = tempAsset.thumbImage;
                UIImage *originImage = tempAsset.originImage;
                NSLog(@"缩略图:%@\n原图:%@",thumbImage,originImage);
                [_photoArr addObject:thumbImage];
            }];
            [_tableView reloadData];
        };

    }
}
- (void)selectFromCamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;

        [self presentViewController:picker animated:YES completion:^{}];
    }else{
        //如果没有提示用户
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您的设备没有相机" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}
#pragma mark--相机拍照
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{

    NSData *imageData = nil;
    UIImage *image = nil;
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(NSString*)kUTTypeImage]){

        image = [info objectForKey:UIImagePickerControllerEditedImage];

        if( image == nil)
        {
            image = [info objectForKey:UIImagePickerControllerOriginalImage];
        }

        NSURL *url = [info objectForKey:UIImagePickerControllerReferenceURL];
        imageData = [NSData dataWithContentsOfFile:url.path];
        if( imageData == nil)
        {
            imageData = UIImageJPEGRepresentation(image, 1);
        }
        else if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(NSString*)kUTTypeMovie]) {

            NSURL* url = [info objectForKey:UIImagePickerControllerMediaURL];
            imageData = [NSData dataWithContentsOfFile:url.path];
        }
        if( image != nil)
        {
            if(image.size.width*image.size.height > 1280*1280*8)
            {
                UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"图片最大不能超过2560x5120!" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
                return;
            }
            else
            {
                image = [image resizedImageToFitInSize:CGSizeMake(1280, 1280) scaleIfSmaller:NO];
                if(image != nil)
                {
                    imageData = UIImageJPEGRepresentation(image, 1);
                }
            }
            [picker dismissViewControllerAnimated:YES completion:^{
                NSLog(@"%@",image);
                [_photoArr addObject:image];
                [_tableView reloadData];
            }];

        }
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark--UITableViewDelegate/UITableViewDatasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    CGFloat height;
    if (_photoArr.count%4!=0) {
        height = (_photoArr.count/4+1)*p_w+(_photoArr.count/4+2)*20;
    }
    else{

        height = (_photoArr.count/4)*p_w+(_photoArr.count/4+1)*20;
    }
    return height;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{


    static NSString *cellID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];

        }
    CGFloat oneX = 20;
    CGFloat oneY = 20;
    for (int i=0; i<_photoArr.count; i++) {
        UIImageView *photoView = [[UIImageView alloc]init];
        [cell.contentView addSubview:photoView];
        int col = i%4;
        int row = i/4;
        CGFloat x = oneX + (p_w+oneX)*col;
        CGFloat y = oneY + (p_w+oneX)*row;
        photoView.frame = CGRectMake(x, y, p_w, p_w);
        [photoView setImage:_photoArr[i]];
    }


    return cell;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

可以获取原图或者缩略图

当做一款APP,需要选择本地图片时,首先考虑的无疑是系统相册,但是Android手机五花八门,再者手机像素的提升,大图无法返回等异常因数,导致适配机型比较困难,微信、QQ都相继的在自己的APP里集成了图片选择功能,放弃了系统提供的图片选择器,这里仿造QQ做了一个本地图片选择器,PS:之前有人说"仿"写成“防”了,今儿特意注意了下,求不错。先上一张效果图,无图无真相啊~~~实现的效果大概是这样的:  1.单选:跳转到本地图片选择文件夹,选择文件夹后,进入到该文件夹下的所有图片,选择某张图片后,返回改图片地址信息  2.多选:跳转到图片文件夹,选择一个文件夹,选择图片,点击右上角的小圆圈,选中该图,点击图片其他区域,查看大图,点击预览,查看已选图片,可以跨文件夹选择图片。 为了达到这效果,需要做几件事:  1.读取本地所有 有图片的文件夹:    这里用ContentResolver读取媒体文件String[] columns = {MediaStore.Images.Media._ID, MediaStore.Images.Thumbnails.DATA, MediaStore.Images.Media.DATA, MediaStore.Images.Media.BUCKET_ID,                         MediaStore.Images.Media.BUCKET_DISPLAY_NAME, "COUNT(1) AS count"};  String selection = "0==0) GROUP BY ("   MediaStore.Images.Media.BUCKET_ID;  String sortOrder = MediaStore.Images.Media.DATE_MODIFIED;  Cursor cursor = contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, selection, null, sortOrder);这是一个简单的SQL查询语句,按文件夹分组,并返回文件夹下图片数。 2.读取指定文件夹下所有图片:  当选择某一目录时,需要读取该目录下所有图片了。String[] columns = new String[]{MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA}; /*查询文件路径包含上面指定的文件夹路径的图片--这样才能保证查询到的文件属于当前文件夹下*/  String whereclause = MediaStore.Images.ImageColumns.DATA   " like'"   folderPath   "/%'";  Log.i("queryGalleryPicture", "galleryPath:"   folderPath);  Cursor corsor = c.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, whereclause, null, null);这里的查询语句是根据文件名字来过滤的,只要图片路径包含文件夹路径的,则为该文件夹下的图片  3.UI交互   首先在展示所有包含图片的文件夹时,异步加载有图片的文件夹,读取成功后列表展示,这里用的RecyclerView展示列表信息,点击某一目录时,在读取改目录下的图片,在图片展示页里,需要注意的是,每次点击判断当前点击图片是否已在选择列表中,若在,删除,不在,添加。这里图片加载用了开源框架ImageLoaderif (mSelectlist.contains(imageBean)) { //点击的item为已选过的图片时,删除                      mSelectlist.remove(imageBean);                      subSelectPosition();                  } else { //不在选择列表里,添加                      if (mSelectlist.size() >= maxCount) {                          Toast.makeText(mContext, mContext.getResources().getString(R.string.publish_select_photo_max, maxCount), Toast.LENGTH_SHORT).show();                          return;                      }                      mSelectlist.add(imageBean);                      imageBean.selectPosition = mSelectlist.size();                  }                  //通知点击项发生了改变                  notifyItemChanged(position);同时没删除一张图片图片上的序号相应的作改变,然后通知改变项更新UI。   不同Activity跳转时,因为要传递图片列表List,list里是自定义实体类,刚开始考虑过用intent传递,但是intent传递后,通过list.get(positon).contains比较是否同一对象时,始终是不同对象,大家可以去验证下。所以这里定义了一个观察者的类,去保存选择的图片和文件夹下的所有图片,同时查看大图时,若选择了一张或者取消选择了一张图,通过观察者通知更新即可/**      * 通知图片选择已改变      */     public void updateImageSelectChanged () {         setChanged();         notifyObservers(imgSelectObj);     }好了,有了以上的,就可以使用我们的图片选择器了:单选时,在需要的地方调用:/*参数对应context, 回调code, 传入的图片List, 可选的最大张数*/ FolderListActivity.startFolderListActivity(this, 1, null, 9);最后Activity的onActivityResult中接收返回的图片数据:List<ImageFolderBean> list = (List<ImageFolderBean>) data.getSerializableExtra("list");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值