iOS开发-简单制作九宫格拼图

时间:2021-12-29 15:36:52

今天闲来无事研究了下拼图,不多说,附代码iOS开发-简单制作九宫格拼图

原图和效果图如下:

iOS开发-简单制作九宫格拼图

 
iOS开发-简单制作九宫格拼图

#define SPACE 2 //小图边距
#define NUMBER 3 //拼图横竖个数

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

[self creatView];
[self segmentImage];
}

//创建背景视图
- (void)creatView
{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(9, 42, 302, 302)];
view.backgroundColor = [UIColor magentaColor];
view.tag = 100;
[self.view addSubview:view];
}

//对图片进行分割
- (void)segmentImage
{
//<1>获取分割的图片
UIImage *image = [UIImage imageNamed:@"king2"];

//<2>获取分割以后的每一小块图片的宽和高
float newImageW = image.size.width / NUMBER;
float newImageH = image.size.height / NUMBER;
NSLog(@"%f",newImageW);
//获取背景视图
UIView *backView = [self.view viewWithTag:100];

//<3>设置number个子视图
for (int i = 0; i < NUMBER; i++)
{
for (int j = 0; j < NUMBER; j++)
{
UIImageView *littleImageView = [[UIImageView alloc] initWithFrame:CGRectMake(SPACE + j * newImageW, SPACE + i * newImageH, newImageW - SPACE, newImageH - SPACE)];

//<4>分割UIImage对象
//CGImageCreateWithImageInRect将UIImge图片按照规定的大小进行分割
//image.CGImage 将UIImage转化成CGImage
CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, littleImageView.frame);

//<5>将CGImage转化成UIImage
UIImage *imageNew = [UIImage imageWithCGImage:imageRef];

//<6>将新获得的小图片 添加在16个UIImageView上
littleImageView.image = imageNew;

//<7>隐藏某个子视图
if (i * j == 4)
{
littleImageView.tag = 998;
littleImageView.hidden = YES;
}

//<8>为所有的imageView视图添加手势
littleImageView.userInteractionEnabled = YES;
[self addGestureRecgonizerOnImageView:littleImageView];

//将16个imageView添加到backView上
[backView addSubview:littleImageView];
}
}
}

//为每一个UIImageView视图添加手势----自定义方法
-(void)addGestureRecgonizerOnImageView:(UIImageView *)imageView
{
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
tap.numberOfTouchesRequired = 1;
tap.numberOfTapsRequired = 1;
[imageView addGestureRecognizer:tap];
}

- (void)tapAction:(UITapGestureRecognizer *)tap
{
UIImageView *imageView = (UIImageView *)tap.view;

//获取空白区域的视图
UIImageView *blockView = (UIImageView *)[self.view viewWithTag:998];

BOOL isEquelX75 = fabs(imageView.frame.origin.x - blockView.frame.origin.x) == 100;
BOOL isEquelY75 = fabs(imageView.frame.origin.y - blockView.frame.origin.y) == 100;
BOOL isEquelX0 = fabs(imageView.frame.origin.x - blockView.frame.origin.x) == 0;
BOOL isEquelY0 = fabs(imageView.frame.origin.y - blockView.frame.origin.y) == 0;

if((isEquelX75 && isEquelY0 ) || (isEquelX0 && isEquelY75))
{
//交换两个子视图的显示位置
[UIView animateWithDuration:0.3 animations:^{

CGRect rect = imageView.frame;
imageView.frame = blockView.frame;
blockView.frame = rect;

} completion:nil];
}

}

@end
最终点击效果

iOS开发-简单制作九宫格拼图