iOS之九宫格图片

照片

现在人们的生活越来越丰富了,很多美好的瞬间都定格在一张张色彩绚丽的照片上,或许把照片珍藏在相册里,或许通过社交软件分享给亲朋好友。那社交软件上的照片是以什么形式展现的呢?那么接下来就要说到九宫格这种形式了。

例图

993270-20160905132230957-78047553.png

照片是加载一个UIView上的,直接上代码了。

YJYComposePhotosView.h文件

#import <UIKit/UIKit.h>

@interface YJYComposePhotosView : UIView
@property (nonatomic, strong)UIImage *image;
@end

YJYComposePhotosView.m文件

#import "YJYComposePhotosView.h"
#import "UIView+Frame.h"

#define ScreenW [UIScreen mainScreen].bounds.size.width

@implementation YJYComposePhotosView

-(void)setImage:(UIImage *)image{
    _image = image;
    UIImageView *imageView = [[UIImageView alloc]init];
    imageView.image = image;
    [self addSubview:imageView];
}
//每添加一个子控件就会调用, 特殊如果在viewDidLoad添加子控件不会调用
-(void)layoutSubviews{
    [super layoutSubviews];

    NSInteger cols = 3;
    CGFloat margin = 10;

    CGFloat wh = (ScreenW - (cols - 1) * margin) / cols;
    CGFloat x = 0;
    CGFloat y = 0;
    NSInteger col = 0;
    NSInteger row = 0;

    for (int i = 0; i < self.subviews.count; i++) {
        UIImageView *imageView = self.subviews[i];
        col = i % cols;
        row  = i / cols;
        x = col * (margin + wh);
        y = row * (margin + wh);
        imageView.frame = CGRectMake(x, y, wh, wh);
    }
}
@end

用法简单

1.导入头文件#import "YJYComposePhotosView.h",定义全局变量@property (nonatomic, strong) YJYComposePhotosView *photosView;
2.创建对象并赋予frame

YJYComposePhotosView *photosView = [[YJYComposePhotosView alloc]initWithFrame:CGRectMake(0, 100, ScreenW, self.view.frame.size.height-64-49)];
_photosView = photosView;
[self.view addSubview:photosView];

3.创建UIImagePickerController并遵循代理<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
imagePicker.delegate = self;
if (imagePicker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
        [self presentViewController:imagePicker animated:YES completion:nil];
    }

4.实现代理方法

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSLog(@"%@", info);
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    _photosView.image = image;
    [self dismissViewControllerAnimated:YES completion:nil];
}

到此大功告成,若需要更加完善的功能和体验,慢慢在区完善吧!

转载于:https://www.cnblogs.com/YaoJinye/p/5841962.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值