iOS之九宫格图片

照片

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

例图

iOS之九宫格图片

照片是加载一个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];
}

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

上一篇:IOS之按钮控件--Button全解析及使用 分类: ios技术 2015-01-17 17:09 169人阅读 评论(0) 收藏


下一篇:iOS面试的算法相关