服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - IOS - iOS中实现动态区域裁剪图片功能实例

iOS中实现动态区域裁剪图片功能实例

2021-04-06 15:31CISay IOS

图片处理中经常用的图片剪裁,就是通过剪裁框确定图片剪裁的区域,然后剪去该区域的图片,下面这篇文章主要给大家介绍了关于iOS中实现动态区域裁剪图片功能的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以

前言

相信大家应该都有所体会,裁剪图片功能在很多上传图片的场景里都需要用到,一方面应用服务器可能对图片的尺寸大小有限制,因而希望上传的图片都是符合规定的,另一方面,用户可能希望只上传图片中的部分内容,突出图片中关键的信息。而为了满足用户多种多样的裁剪需求,就需要裁剪图片时能支持由用户动态地改变裁剪范围、裁剪尺寸等。

动态裁剪图片的基本过程大致可以分为以下几步

  • 显示图片与裁剪区域
  • 支持移动和缩放图片
  • 支持手势改变裁剪区域
  • 进行图片裁剪并获得裁剪后的图片

显示图片与裁剪区域

显示图片

在裁剪图片之前,首先我们要在页面上显示待裁剪的图片,如下图所示

iOS中实现动态区域裁剪图片功能实例

这一步比较简单,配置一个 uiimageview 来放置图片即可。但是要注意一点,uiimageview 有多种 contentmode,最常见有三种

  • uiviewcontentmodescaletofill
  • uiviewcontentmodescaleaspectfit
  • uiviewcontentmodescaleaspectfill

三者区别可以看下面的比较

uiviewcontentmodescaletofill

iOS中实现动态区域裁剪图片功能实例

uiviewcontentmodescaleaspectfit

iOS中实现动态区域裁剪图片功能实例

uiviewcontentmodescaleaspectfill

iOS中实现动态区域裁剪图片功能实例

可以看出,scaletofill 会改变图片的长宽比例来铺满整个 uiimageview,scaleaspectfill 则会保持图片比例来铺满,从而会有部分图片内容超出 uiimageview 区域的情况,而 scaleaspectfit 则会保证图片比例不变,同时图片内容都显示在 uiimageview 中,即使无法铺满 uiimageview。

因此不同显示模式会影响到我们最终显示到屏幕上的图片的样子,而在裁剪过程中最理想的放置图片的模式则是,图片的短边刚好铺满裁剪区域的短边,而长边至少不会小于裁剪区域的长边,这就要求我们要考虑裁剪区域的长宽来放置我们的图片。

裁剪区域

接下来我们要放置我们的裁剪区域,它的样子如下所示

iOS中实现动态区域裁剪图片功能实例

裁剪区域本身就是在 uiimageview 上放上一层 uiview,再在 uiview 上绘制出一个白边框的方格 layer。

首先自定义一个 cashapelayer

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#import <quartzcore/quartzcore.h>
 
@interface yasiccliparealayer : cashapelayer
 
@property(assign, nonatomic) nsinteger croparealeft;
@property(assign, nonatomic) nsinteger cropareatop;
@property(assign, nonatomic) nsinteger croparearight;
@property(assign, nonatomic) nsinteger cropareabottom;
 
- (void)setcroparealeft:(nsinteger)croparealeft cropareatop:(nsinteger)cropareatop croparearight:(nsinteger)croparearight cropareabottom:(nsinteger)cropareabottom;
 
 
@end
 
@implementation yasiccliparealayer
 
- (instancetype)init
{
 self = [super init];
 if (self) {
 _croparealeft = 50;
 _cropareatop = 50;
 _croparearight = screen_width - self.croparealeft;
 _cropareabottom = 400;
 }
 return self;
}
 
- (void)drawincontext:(cgcontextref)ctx
{
 uigraphicspushcontext(ctx);
 
 cgcontextsetstrokecolorwithcolor(ctx, [uicolor whitecolor].cgcolor);
 cgcontextsetlinewidth(ctx, linewidth);
 cgcontextmovetopoint(ctx, self.croparealeft, self.cropareatop);
 cgcontextaddlinetopoint(ctx, self.croparealeft, self.cropareabottom);
 cgcontextsetshadow(ctx, cgsizemake(2, 0), 2.0);
 cgcontextstrokepath(ctx);
 
 cgcontextsetstrokecolorwithcolor(ctx, [uicolor whitecolor].cgcolor);
 cgcontextsetlinewidth(ctx, linewidth);
 cgcontextmovetopoint(ctx, self.croparealeft, self.cropareatop);
 cgcontextaddlinetopoint(ctx, self.croparearight, self.cropareatop);
 cgcontextsetshadow(ctx, cgsizemake(0, 2), 2.0);
 cgcontextstrokepath(ctx);
 
 cgcontextsetstrokecolorwithcolor(ctx, [uicolor whitecolor].cgcolor);
 cgcontextsetlinewidth(ctx, linewidth);
 cgcontextmovetopoint(ctx, self.croparearight, self.cropareatop);
 cgcontextaddlinetopoint(ctx, self.croparearight, self.cropareabottom);
 cgcontextsetshadow(ctx, cgsizemake(-2, 0), 2.0);
 cgcontextstrokepath(ctx);
 
 cgcontextsetstrokecolorwithcolor(ctx, [uicolor whitecolor].cgcolor);
 cgcontextsetlinewidth(ctx, linewidth);
 cgcontextmovetopoint(ctx, self.croparealeft, self.cropareabottom);
 cgcontextaddlinetopoint(ctx, self.croparearight, self.cropareabottom);
 cgcontextsetshadow(ctx, cgsizemake(0, -2), 2.0);
 cgcontextstrokepath(ctx);
 
 uigraphicspopcontext();
}
 
- (void)setcroparealeft:(nsinteger)croparealeft
{
 _croparealeft = croparealeft;
 [self setneedsdisplay];
}
 
- (void)setcropareatop:(nsinteger)cropareatop
{
 _cropareatop = cropareatop;
 [self setneedsdisplay];
}
 
- (void)setcroparearight:(nsinteger)croparearight
{
 _croparearight = croparearight;
 [self setneedsdisplay];
}
 
- (void)setcropareabottom:(nsinteger)cropareabottom
{
 _cropareabottom = cropareabottom;
 [self setneedsdisplay];
}
 
- (void)setcroparealeft:(nsinteger)croparealeft cropareatop:(nsinteger)cropareatop croparearight:(nsinteger)croparearight cropareabottom:(nsinteger)cropareabottom
{
 _croparealeft = croparealeft;
 _croparearight = croparearight;
 _cropareatop = cropareatop;
 _cropareabottom = cropareabottom;
 
 [self setneedsdisplay];
}
 
@end

这里 layer 有几个属性 croparealeft、croparearight、cropareatop、cropareabottom,从命名上可以看出这几个属性定义了这个 layer 上绘制的白边框裁剪区域的坐标信息。还暴露了一个方法用于配置这四个属性。

然后在 cashapelayer 内部,重点在于复写 drawincontext 方法,这个方法负责直接在图层上绘图,复写的方法主要做的事情是根据上面四个属性 croparealeft、croparearight、cropareatop、cropareabottom 绘制出封闭的四条线,这样就能表示裁剪区域的边界了。

要注意的是 drawincontext 方法不能手动显示调用,必须通过调用 setneedsdisplay 或者 setneedsdisplayinrect 让系统自动调该方法。

在裁剪页面里,我们放置了一个 cropview,然后将自定义的 cashaplayer 加入到这个 view 上

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
self.cropview.layer.sublayers = nil;
yasiccliparealayer * layer = [[yasiccliparealayer alloc] init];
 
cgrect cropframe = cgrectmake(self.cropareax, self.cropareay, self.cropareawidth, self.cropareaheight);
uibezierpath * path = [uibezierpath bezierpathwithroundedrect:self.cropview.frame cornerradius:0];
uibezierpath * croppath = [uibezierpath bezierpathwithrect:cropframe];
[path appendpath:croppath];
layer.path = path.cgpath;
 
layer.fillrule = kcafillruleevenodd;
layer.fillcolor = [[uicolor blackcolor] cgcolor];
layer.opacity = 0.5;
 
layer.frame = self.cropview.bounds;
[layer setcroparealeft:self.cropareax cropareatop:self.cropareay croparearight:self.cropareax + self.cropareawidth cropareabottom:self.cropareay + self.cropareaheight];
[self.cropview.layer addsublayer:layer];
[self.view bringsubviewtofront:self.cropview];

这里主要是为了用自定义的 cashapelayer 产生出空心遮罩的效果,从而出现中心的裁剪区域高亮而四周非裁剪区域有蒙层的效果,示意图如下

iOS中实现动态区域裁剪图片功能实例

所以首先确定了 cashapelayer 的大小为 cropview 的大小,生成一个对应的 uibezierpath,然后根据裁剪区域的大小(由 self.cropareax, self.cropareay, self.cropareawidth, self.cropareaheight 确定)生成空心遮罩的内圈 uibezierpath,

?
1
2
3
4
5
cgrect cropframe = cgrectmake(self.cropareax, self.cropareay, self.cropareawidth, self.cropareaheight);
 uibezierpath * path = [uibezierpath bezierpathwithroundedrect:self.cropview.frame cornerradius:0];
 uibezierpath * croppath = [uibezierpath bezierpathwithrect:cropframe];
 [path appendpath:croppath];
 layer.path = path.cgpath;

然后将这个 path 配置给 cashapelayer,并将 cashapelayer 的 fillrule 配置为 kcafillruleevenodd

?
1
2
3
4
layer.fillrule = kcafillruleevenodd;
layer.fillcolor = [[uicolor blackcolor] cgcolor];
layer.opacity = 0.5;
layer.frame = self.cropview.bounds;

其中 fillrule 属性表示使用哪一种算法去判断画布上的某区域是否属于该图形“内部”,内部区域将被填充颜色,主要有两种方式

kcafillrulenonzero,这种算法判断规则是,如果从某一点射出任意方向射线,与对应 layer 交点为 0 则不在 layer 内,大于 0 则在 画布内

iOS中实现动态区域裁剪图片功能实例

kcafillruleevenodd 如果从某一点射出任意射线,与对应 layer 交点为偶数则在画布内,否则不在画布内

iOS中实现动态区域裁剪图片功能实例

再给 cashapelayer 设置蒙层颜色为透明度 0.5 的黑色,就可以实现空心蒙层效果了。

最后就是设置 layer 的四个属性并绘制内边框的白色边线。

?
1
2
3
[layer setcroparealeft:self.cropareax cropareatop:self.cropareay croparearight:self.cropareax + self.cropareawidth cropareabottom:self.cropareay + self.cropareaheight];
[self.cropview.layer addsublayer:layer];
[self.view bringsubviewtofront:self.cropview];

合理放置图片

到这一步我们正确显示了图片,也正确显示出了裁剪区域,但是我们没有将二者的约束关系建立起来,因此可能会出现下面这样的情况

iOS中实现动态区域裁剪图片功能实例

可以看到这里由于这张图片的 width 远大于 height,因此会在裁剪区域内出现黑色区域,这对用户来说是一种不好的体验,同时也会影响到我们后面的裁剪步骤,究其原因是因为我们没有针对裁剪区域的宽高来放置 uiimageview,我们希望最理想的效果是,能在裁剪区域内实现类似 uiviewcontentmodescaleaspectfill 的效果,也就是图片保持比例地铺满裁剪区域,并允许部分内容超出裁剪区域,这就要求

  • 当图片宽与裁剪区域宽之比大于图片高与裁剪区域高之比时,将图片高铺满裁剪区域高,图片宽成比例放大
  • 当图片高与裁剪区域高之比大于图片宽与裁剪区域宽之比时,将图片宽铺满裁剪区域宽,图片高成比例方法

这里我们用到 masonry 来做这些布局操作

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
cgfloat tempwidth = 0.0;
cgfloat tempheight = 0.0;
 
if (self.targetimage.size.width/self.cropareawidth <= self.targetimage.size.height/self.cropareaheight) {
tempwidth = self.cropareawidth;
tempheight = (tempwidth/self.targetimage.size.width) * self.targetimage.size.height;
} else if (self.targetimage.size.width/self.cropareawidth > self.targetimage.size.height/self.cropareaheight) {
tempheight = self.cropareaheight;
tempwidth = (tempheight/self.targetimage.size.height) * self.targetimage.size.width;
}
 
[self.bigimageview mas_updateconstraints:^(masconstraintmaker *make) {
make.left.mas_equalto(self.cropareax - (tempwidth - self.cropareawidth)/2);
make.top.mas_equalto(self.cropareay - (tempheight - self.cropareaheight)/2);
make.width.mas_equalto(tempwidth);
make.height.mas_equalto(tempheight);
}];

可以看到,我们进行了两步判断,从而获得合适的宽高值,然后将图片进行布局,在自动布局时将图片中心与裁剪区域中心重合,最后我们会得到下面的效果图

iOS中实现动态区域裁剪图片功能实例

支持移动和缩放图片

正如上面所讲,由于图片在裁剪区域内是以类似 uiviewcontentmodescaleaspectfill 的方式放置的,很可能出现部分内容溢出裁剪区域,因此我们要让图片能支持动态移动和缩放,从而使用户能灵活地裁剪图片的内容。

具体实现上,我们其实是在 cropview 上加上手势,间接操作图片的尺寸和位置,这样有助于后面我们实现动态改变裁剪区域的实现。

缩放功能

这里实现缩放的原理实际是对放置图片的 uiimageview 的 frame 进行修改,首先我们要记录下最初的 uiimageview 的 frame

?
1
self.originalframe = cgrectmake(self.cropareax - (tempwidth - self.cropareawidth)/2, self.cropareay - (tempheight - self.cropareaheight)/2, tempwidth, tempheight);

然后为 cropview 添加手势

?
1
2
3
// 捏合手势
uipinchgesturerecognizer *pingesture = [[uipinchgesturerecognizer alloc] initwithtarget:self action:@selector(handlecenterpingesture:)];
[self.view addgesturerecognizer:pingesture];

然后是手势处理函数

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
-(void)handlecenterpingesture:(uipinchgesturerecognizer *)pingesture
{
 cgfloat scaleration = 3;
 uiview * view = self.bigimageview;
 
 // 缩放开始与缩放中
 if (pingesture.state == uigesturerecognizerstatebegan || pingesture.state == uigesturerecognizerstatechanged) {
 // 移动缩放中心到手指中心
 cgpoint pinchcenter = [pingesture locationinview:view.superview];
 cgfloat distancex = view.frame.origin.x - pinchcenter.x;
 cgfloat distancey = view.frame.origin.y - pinchcenter.y;
 cgfloat scaleddistancex = distancex * pingesture.scale;
 cgfloat scaleddistancey = distancey * pingesture.scale;
 cgrect newframe = cgrectmake(view.frame.origin.x + scaleddistancex - distancex, view.frame.origin.y + scaleddistancey - distancey, view.frame.size.width * pingesture.scale, view.frame.size.height * pingesture.scale);
 view.frame = newframe;
 pingesture.scale = 1;
 }
 
 // 缩放结束
 if (pingesture.state == uigesturerecognizerstateended) {
 cgfloat ration = view.frame.size.width / self.originalframe.size.width;
 
 // 缩放过大
 if (ration > 5) {
 cgrect newframe = cgrectmake(0, 0, self.originalframe.size.width * scaleration, self.originalframe.size.height * scaleration);
 view.frame = newframe;
 }
 
 // 缩放过小
 if (ration < 0.25) {
 view.frame = self.originalframe;
 }
 // 对图片进行位置修正
 cgrect resetposition = cgrectmake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, view.frame.size.height);
 
 if (resetposition.origin.x >= self.cropareax) {
 resetposition.origin.x = self.cropareax;
 }
 if (resetposition.origin.y >= self.cropareay) {
 resetposition.origin.y = self.cropareay;
 }
 if (resetposition.size.width + resetposition.origin.x < self.cropareax + self.cropareawidth) {
 cgfloat movedleftx = fabs(resetposition.size.width + resetposition.origin.x - (self.cropareax + self.cropareawidth));
 resetposition.origin.x += movedleftx;
 }
 if (resetposition.size.height + resetposition.origin.y < self.cropareay + self.cropareaheight) {
 cgfloat moveupy = fabs(resetposition.size.height + resetposition.origin.y - (self.cropareay + self.cropareaheight));
 resetposition.origin.y += moveupy;
 }
 view.frame = resetposition;
 
 // 对图片缩放进行比例修正,防止过小
 if (self.cropareax < self.bigimageview.frame.origin.x
 || ((self.cropareax + self.cropareawidth) > self.bigimageview.frame.origin.x + self.bigimageview.frame.size.width)
 || self.cropareay < self.bigimageview.frame.origin.y
 || ((self.cropareay + self.cropareaheight) > self.bigimageview.frame.origin.y + self.bigimageview.frame.size.height)) {
 view.frame = self.originalframe;
 }
 }
}

在手势处理时,要注意,为了能跟随用户捏合手势的中心进行缩放,我们要在手势过程中移动缩放中心到手指中心,这里我们判断了 pingesture 的 state 来确定手势开始、进行中和结束阶段。

?
1
2
3
4
5
6
7
8
9
10
11
if (pingesture.state == uigesturerecognizerstatebegan || pingesture.state == uigesturerecognizerstatechanged) {
// 移动缩放中心到手指中心
cgpoint pinchcenter = [pingesture locationinview:view.superview];
cgfloat distancex = view.frame.origin.x - pinchcenter.x;
cgfloat distancey = view.frame.origin.y - pinchcenter.y;
cgfloat scaleddistancex = distancex * pingesture.scale;
cgfloat scaleddistancey = distancey * pingesture.scale;
cgrect newframe = cgrectmake(view.frame.origin.x + scaleddistancex - distancex, view.frame.origin.y + scaleddistancey - distancey, view.frame.size.width * pingesture.scale, view.frame.size.height * pingesture.scale);
view.frame = newframe;
pingesture.scale = 1;
}

pinchcenter 就是捏合手势的中心,我们获取到当前图片 view 的 frame,然后计算当前 view 与手势中心的 x、y 坐标差,再根据手势缩放值 scale,创建出新的 frame

?
1
cgrect newframe = cgrectmake(view.frame.origin.x + scaleddistancex - distancex, view.frame.origin.y + scaleddistancey - distancey, view.frame.size.width * pingesture.scale, view.frame.size.height * pingesture.scale);

这个 frame 的中心坐标就在缩放手势的中心,将新的 frame 赋值给图片 view,从而实现依据手势中心进行缩放的效果。

而在手势结束阶段,我们要对图片缩放进行边界保护,既不能放大过大,也不能缩小过小。

?
1
2
3
4
5
6
7
8
9
10
11
12
cgfloat ration = view.frame.size.width / self.originalframe.size.width;
 
 // 缩放过大
 if (ration > 5) {
 cgrect newframe = cgrectmake(0, 0, self.originalframe.size.width * scaleration, self.originalframe.size.height * scaleration);
 view.frame = newframe;
 }
 
 // 缩放过小
 if (ration < 0.25) {
 view.frame = self.originalframe;
 }

同时缩放后如果图片与裁剪区域出现了空白区域,还要对图片的位置进行修正以保证图片始终是覆盖全裁剪区域的。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 对图片进行位置修正
 cgrect resetposition = cgrectmake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, view.frame.size.height);
 
 if (resetposition.origin.x >= self.cropareax) {
  resetposition.origin.x = self.cropareax;
 }
 if (resetposition.origin.y >= self.cropareay) {
  resetposition.origin.y = self.cropareay;
 }
 if (resetposition.size.width + resetposition.origin.x < self.cropareax + self.cropareawidth) {
  cgfloat movedleftx = fabs(resetposition.size.width + resetposition.origin.x - (self.cropareax + self.cropareawidth));
  resetposition.origin.x += movedleftx;
 }
 if (resetposition.size.height + resetposition.origin.y < self.cropareay + self.cropareaheight) {
  cgfloat moveupy = fabs(resetposition.size.height + resetposition.origin.y - (self.cropareay + self.cropareaheight));
  resetposition.origin.y += moveupy;
 }
 view.frame = resetposition;

这里我们通过生成当前图片的 cgrect,与裁剪区域的边界进行如下比较

  • 图片左边线大于裁剪区域左边线时图片移动到裁剪区域 x 值
  • 图片上边线大于裁剪区域上边线时图片移动到裁剪区域 y 值
  • 图片右边线小于裁剪区域右边线时图片右贴裁剪区域右边线
  • 图片下边线小于裁剪区域右边线时图片下贴裁剪区域下边线

进行这番操作后,可能会出现由于图片过小无法铺满裁剪区域的情况,如下图所示

iOS中实现动态区域裁剪图片功能实例

因此还需要再次对图片尺寸进行修正

?
1
2
3
4
5
6
7
// 对图片缩放进行比例修正,防止过小
if (self.cropareax < self.bigimageview.frame.origin.x
 || ((self.cropareax + self.cropareawidth) > self.bigimageview.frame.origin.x + self.bigimageview.frame.size.width)
 || self.cropareay < self.bigimageview.frame.origin.y
 || ((self.cropareay + self.cropareaheight) > self.bigimageview.frame.origin.y + self.bigimageview.frame.size.height)) {
 view.frame = self.originalframe;
}

这样就实现了缩放功能。

移动功能

相比于缩放,移动功能实现就简单了,只需要在 cropview 上添加 uipangesturerecognizer,然后在回调方法里拿到需要移动的距离,修改 uiimageview 的 center 就可以了。

?
1
2
3
cgpoint translation = [pangesture translationinview:view.superview];
[view setcenter:cgpointmake(view.center.x + translation.x, view.center.y + translation.y)];
 [pangesture settranslation:cgpointzero inview:view.superview];

但是同样为了保证移动后的图片不会与裁剪区域出现空白甚至是超出裁剪区域,这里更新了图片位置后,在手势结束时还要对图片进行位置修正

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
cgrect currentframe = view.frame;
 
if (currentframe.origin.x >= self.cropareax) {
 currentframe.origin.x = self.cropareax;
 
}
if (currentframe.origin.y >= self.cropareay) {
 currentframe.origin.y = self.cropareay;
}
if (currentframe.size.width + currentframe.origin.x < self.cropareax + self.cropareawidth) {
 cgfloat movedleftx = fabs(currentframe.size.width + currentframe.origin.x - (self.cropareax + self.cropareawidth));
 currentframe.origin.x += movedleftx;
}
if (currentframe.size.height + currentframe.origin.y < self.cropareay + self.cropareaheight) {
 cgfloat moveupy = fabs(currentframe.size.height + currentframe.origin.y - (self.cropareay + self.cropareaheight));
 currentframe.origin.y += moveupy;
}
[uiview animatewithduration:0.3 animations:^{
 
 [view setframe:currentframe];
}];

可以看到,这里做的位置检查与缩放时做的检查是一样的,只是由于不会改变图片尺寸所以这里不需要进行尺寸修正。

支持手势改变裁剪区域

接下来就是动态裁剪图片的核心内容了,其实原理也很简单,只要在上面的移动手势处理函数中,进行一些判断,决定是移动图片位置还是改变裁剪区域,也就是自定义的 cashapelayer 的绘制方框的尺寸就可以了。

首先我们定义一个枚举,用来表示当前应当操作的是图片还是裁剪区域的边线

?
1
2
3
4
5
6
7
typedef ns_enum(nsinteger, activegestureview) {
 cropviewleft,
 cropviewright,
 cropviewtop,
 cropviewbottom,
 bigimageview
};

它们分别表示触发对象为裁剪区域左边线、右边线、上边线、下边线以及 uiimageview

然后我们定义一个枚举属性

?
1
@property(assign, nonatomic) activegestureview activegestureview;

判断操作对象的标准是当前的手势所触发的位置是在边线上还是在非边线上,因此我们需要知道手势触发时的坐标,要知道这一点就需要我们继承一个 uipangesturerecognizer 并覆写一些方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
@interface yasicpangesturerecognizer : uipangesturerecognizer
 
@property(assign, nonatomic) cgpoint beginpoint;
@property(assign, nonatomic) cgpoint movepoint;
 
-(instancetype)initwithtarget:(id)target action:(sel)action inview:(uiview*)view;
 
@end
 
@interface yasicpangesturerecognizer()
 
@property(strong, nonatomic) uiview *targetview;
 
@end
 
@implementation yasicpangesturerecognizer
 
-(instancetype)initwithtarget:(id)target action:(sel)action inview:(uiview*)view{
 
 self = [super initwithtarget:target action:action];
 if(self) {
 self.targetview = view;
 }
 return self;
}
 
- (void)touchesbegan:(nsset *)touches withevent:(uievent*)event{
 
 [super touchesbegan:touches withevent:event];
 uitouch *touch = [touches anyobject];
 self.beginpoint = [touch locationinview:self.targetview];
}
 
- (void)touchesmoved:(nsset<uitouch *> *)touches withevent:(uievent *)event
{
 [super touchesmoved:touches withevent:event];
 uitouch *touch = [touches anyobject];
 self.movepoint = [touch locationinview:self.targetview];
}
 
@end

可以看到,我们首先传入了一个 view,用于将手势触发的位置转换为 view 中的坐标值。在 - (void)touchesbegan:(nsset *)touches withevent:(uievent*)event{ 方法中我们得到了手势开始时的触发点 beginpoint,在 - (void)touchesmoved:(nsset<uitouch *> *)touches withevent:(uievent *)event 方法中我们获得了手势进行时的触发点 movepoint。

自定义完 uipangesturerecognizer 后我们将其加到 cropview 上并把 cropview 作为参数传给 uipangesturerecognizer

?
1
2
3
// 拖动手势
yasicpangesturerecognizer *pangesture = [[yasicpangesturerecognizer alloc] initwithtarget:self action:@selector(handledynamicpangesture:) inview:self.cropview];
[self.cropview addgesturerecognizer:pangesture];

接下来就是处理手势的函数,这里我们可以将整个过程分为三个步骤,开始时 -> 进行时 -> 结束时。

手势开始时

在这里我们要根据手势的 beginpoint 判断触发对象是边线还是 uiimageview

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 开始滑动时判断滑动对象是 imageview 还是 layer 上的 line
 if (pangesture.state == uigesturerecognizerstatebegan) {
 if (beginpoint.x >= self.cropareax - judgewidth && beginpoint.x <= self.cropareax + judgewidth && beginpoint.y >= self.cropareay && beginpoint.y <= self.cropareay + self.cropareaheight && self.cropareawidth >= 50) {
  self.activegestureview = cropviewleft;
 } else if (beginpoint.x >= self.cropareax + self.cropareawidth - judgewidth && beginpoint.x <= self.cropareax + self.cropareawidth + judgewidth && beginpoint.y >= self.cropareay && beginpoint.y <= self.cropareay + self.cropareaheight && self.cropareawidth >= 50) {
  self.activegestureview = cropviewright;
 } else if (beginpoint.y >= self.cropareay - judgewidth && beginpoint.y <= self.cropareay + judgewidth && beginpoint.x >= self.cropareax && beginpoint.x <= self.cropareax + self.cropareawidth && self.cropareaheight >= 50) {
  self.activegestureview = cropviewtop;
 } else if (beginpoint.y >= self.cropareay + self.cropareaheight - judgewidth && beginpoint.y <= self.cropareay + self.cropareaheight + judgewidth && beginpoint.x >= self.cropareax && beginpoint.x <= self.cropareax + self.cropareawidth && self.cropareaheight >= 50) {
  self.activegestureview = cropviewbottom;
 } else {
  self.activegestureview = bigimageview;
  [view setcenter:cgpointmake(view.center.x + translation.x, view.center.y + translation.y)];
  [pangesture settranslation:cgpointzero inview:view.superview];
 }
 }

手势进行时

在这里,如果触发对象是边线,则计算边线需要移动的距离和方向,以及对于边界条件的限制以防止边线之间交叉错位的情况,具体来说就是获得坐标差值,更新 cropareax、cropareawidth 等值,然后更新 cashapelayer 上的空心蒙层。

如果触发对象是 uiimageview 则只需要将其位置进行改变即可。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// 滑动过程中进行位置改变
 if (pangesture.state == uigesturerecognizerstatechanged) {
 cgfloat diff = 0;
 switch (self.activegestureview) {
  case cropviewleft: {
  diff = movepoint.x - self.cropareax;
  if (diff >= 0 && self.cropareawidth > 50) {
   self.cropareawidth -= diff;
   self.cropareax += diff;
  } else if (diff < 0 && self.cropareax > self.bigimageview.frame.origin.x && self.cropareax >= 15) {
   self.cropareawidth -= diff;
   self.cropareax += diff;
  }
  [self setupcroplayer];
  break;
  }
  case cropviewright: {
  diff = movepoint.x - self.cropareax - self.cropareawidth;
  if (diff >= 0 && (self.cropareax + self.cropareawidth) < min(self.bigimageview.frame.origin.x + self.bigimageview.frame.size.width, self.cropview.frame.origin.x + self.cropview.frame.size.width - 15)){
   self.cropareawidth += diff;
  } else if (diff < 0 && self.cropareawidth >= 50) {
   self.cropareawidth += diff;
  }
  [self setupcroplayer];
  break;
  }
  case cropviewtop: {
  diff = movepoint.y - self.cropareay;
  if (diff >= 0 && self.cropareaheight > 50) {
   self.cropareaheight -= diff;
   self.cropareay += diff;
  } else if (diff < 0 && self.cropareay > self.bigimageview.frame.origin.y && self.cropareay >= 15) {
   self.cropareaheight -= diff;
   self.cropareay += diff;
  }
  [self setupcroplayer];
  break;
  }
  case cropviewbottom: {
  diff = movepoint.y - self.cropareay - self.cropareaheight;
  if (diff >= 0 && (self.cropareay + self.cropareaheight) < min(self.bigimageview.frame.origin.y + self.bigimageview.frame.size.height, self.cropview.frame.origin.y + self.cropview.frame.size.height - 15)){
   self.cropareaheight += diff;
  } else if (diff < 0 && self.cropareaheight >= 50) {
   self.cropareaheight += diff;
  }
  [self setupcroplayer];
  break;
  }
  case bigimageview: {
  [view setcenter:cgpointmake(view.center.x + translation.x, view.center.y + translation.y)];
  [pangesture settranslation:cgpointzero inview:view.superview];
  break;
  }
  default:
  break;
 }
 }

手势结束时

手势结束时,我们需要对位置进行修正。如果是裁剪区域边线,则要判断左右、上下边线之间的距离是否过短,边线是否超出 uiimageview 的范围等。如果左右边线距离过短则设置最小裁剪宽度,如果上线边线距离过短则设置最小裁剪高度,如果左边线超出了 uiimageview 左边线则需要紧贴 uiimageview 的左边线,并更新裁剪区域宽度,以此类推。然后更新 cashapelayer 上的空心蒙层即可。

如果是 uiimageview 则跟上一节一样要保证图片不会与裁剪区域出现空白。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// 滑动结束后进行位置修正
if (pangesture.state == uigesturerecognizerstateended) {
switch (self.activegestureview) {
 case cropviewleft: {
 if (self.cropareawidth < 50) {
  self.cropareax -= 50 - self.cropareawidth;
  self.cropareawidth = 50;
 }
 if (self.cropareax < max(self.bigimageview.frame.origin.x, 15)) {
  cgfloat temp = self.cropareax + self.cropareawidth;
  self.cropareax = max(self.bigimageview.frame.origin.x, 15);
  self.cropareawidth = temp - self.cropareax;
 }
 [self setupcroplayer];
 break;
 }
 case cropviewright: {
 if (self.cropareawidth < 50) {
  self.cropareawidth = 50;
 }
 if (self.cropareax + self.cropareawidth > min(self.bigimageview.frame.origin.x + self.bigimageview.frame.size.width, self.cropview.frame.origin.x + self.cropview.frame.size.width - 15)) {
  self.cropareawidth = min(self.bigimageview.frame.origin.x + self.bigimageview.frame.size.width, self.cropview.frame.origin.x + self.cropview.frame.size.width - 15) - self.cropareax;
 }
 [self setupcroplayer];
 break;
 }
 case cropviewtop: {
 if (self.cropareaheight < 50) {
  self.cropareay -= 50 - self.cropareaheight;
  self.cropareaheight = 50;
 }
 if (self.cropareay < max(self.bigimageview.frame.origin.y, 15)) {
  cgfloat temp = self.cropareay + self.cropareaheight;
  self.cropareay = max(self.bigimageview.frame.origin.y, 15);
  self.cropareaheight = temp - self.cropareay;
 }
 [self setupcroplayer];
 break;
 }
 case cropviewbottom: {
 if (self.cropareaheight < 50) {
  self.cropareaheight = 50;
 }
 if (self.cropareay + self.cropareaheight > min(self.bigimageview.frame.origin.y + self.bigimageview.frame.size.height, self.cropview.frame.origin.y + self.cropview.frame.size.height - 15)) {
  self.cropareaheight = min(self.bigimageview.frame.origin.y + self.bigimageview.frame.size.height, self.cropview.frame.origin.y + self.cropview.frame.size.height - 15) - self.cropareay;
 }
 [self setupcroplayer];
 break;
 }
 case bigimageview: {
 cgrect currentframe = view.frame;
 
 if (currentframe.origin.x >= self.cropareax) {
  currentframe.origin.x = self.cropareax;
  
 }
 if (currentframe.origin.y >= self.cropareay) {
  currentframe.origin.y = self.cropareay;
 }
 if (currentframe.size.width + currentframe.origin.x < self.cropareax + self.cropareawidth) {
  cgfloat movedleftx = fabs(currentframe.size.width + currentframe.origin.x - (self.cropareax + self.cropareawidth));
  currentframe.origin.x += movedleftx;
 }
 if (currentframe.size.height + currentframe.origin.y < self.cropareay + self.cropareaheight) {
  cgfloat moveupy = fabs(currentframe.size.height + currentframe.origin.y - (self.cropareay + self.cropareaheight));
  currentframe.origin.y += moveupy;
 }
 [uiview animatewithduration:0.3 animations:^{
  
  [view setframe:currentframe];
 }];
 break;
 }
 default:
 break;
}
}

进行图片裁剪并获得裁剪后的图片

最后一步就是对图片进行裁剪了。首先确定对图片的缩放尺寸 imagescale

?
1
cgfloat imagescale = min(self.bigimageview.frame.size.width/self.targetimage.size.width, self.bigimageview.frame.size.height/self.targetimage.size.height);

然后将 cropview 的裁剪区域对应到 uiimageview 上,再除以缩放值,即可得到对应 uiimage 上需要裁剪的区域

?
1
2
3
4
5
cgfloat cropx = (self.cropareax - self.bigimageview.frame.origin.x)/imagescale;
cgfloat cropy = (self.cropareay - self.bigimageview.frame.origin.y)/imagescale;
cgfloat cropwidth = self.cropareawidth/imagescale;
cgfloat cropheight = self.cropareaheight/imagescale;
cgrect croprect = cgrectmake(cropx, cropy, cropwidth, cropheight);

最后调用 coregraphic 的方法,将图片对应区域的数据取出来生成新的图片,就是我们需要的裁剪后的图片了。

?
1
2
3
cgimageref sourceimageref = [self.targetimage cgimage];
cgimageref newimageref = cgimagecreatewithimageinrect(sourceimageref, croprect);
uiimage *newimage = [uiimage imagewithcgimage:newimageref];

源码下载:

github下载地址:点击这里

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

原文链接:http://www.jianshu.com/p/73043c1d869a

延伸 · 阅读

精彩推荐
  • IOS关于iOS自适应cell行高的那些事儿

    关于iOS自适应cell行高的那些事儿

    这篇文章主要给大家介绍了关于iOS自适应cell行高的那些事儿,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的...

    daisy6092021-05-17
  • IOSiOS布局渲染之UIView方法的调用时机详解

    iOS布局渲染之UIView方法的调用时机详解

    在你刚开始开发 iOS 应用时,最难避免或者是调试的就是和布局相关的问题,下面这篇文章主要给大家介绍了关于iOS布局渲染之UIView方法调用时机的相关资料...

    windtersharp7642021-05-04
  • IOSIOS开发之字典转字符串的实例详解

    IOS开发之字典转字符串的实例详解

    这篇文章主要介绍了IOS开发之字典转字符串的实例详解的相关资料,希望通过本文能帮助到大家,让大家掌握这样的方法,需要的朋友可以参考下...

    苦练内功5832021-04-01
  • IOS解析iOS开发中的FirstResponder第一响应对象

    解析iOS开发中的FirstResponder第一响应对象

    这篇文章主要介绍了解析iOS开发中的FirstResponder第一响应对象,包括View的FirstResponder的释放问题,需要的朋友可以参考下...

    一片枫叶4662020-12-25
  • IOSiOS中tableview 两级cell的展开与收回的示例代码

    iOS中tableview 两级cell的展开与收回的示例代码

    本篇文章主要介绍了iOS中tableview 两级cell的展开与收回的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    J_Kang3862021-04-22
  • IOSIOS 屏幕适配方案实现缩放window的示例代码

    IOS 屏幕适配方案实现缩放window的示例代码

    这篇文章主要介绍了IOS 屏幕适配方案实现缩放window的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要...

    xiari5772021-06-01
  • IOSiOS通过逆向理解Block的内存模型

    iOS通过逆向理解Block的内存模型

    自从对 iOS 的逆向初窥门径后,我也经常通过它来分析一些比较大的应用,参考一下这些应用中某些功能的实现。这个探索的过程乐趣多多,不仅能满足自...

    Swiftyper12832021-03-03
  • IOSiOS 雷达效果实例详解

    iOS 雷达效果实例详解

    这篇文章主要介绍了iOS 雷达效果实例详解的相关资料,需要的朋友可以参考下...

    SimpleWorld11022021-01-28