欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS实现图片六边形阴影效果

程序员文章站 2023-12-16 21:10:52
先来看看效果图 这个效果写起来挺简单,主要运用下面几个知识点      layer 的mask : 图层蒙版  ...

先来看看效果图

iOS实现图片六边形阴影效果

这个效果写起来挺简单,主要运用下面几个知识点

     layer mask : 图层蒙版

     layer shadowpath : 绘制自定义形状阴影

     uibezierpath :绘制六边形路线

说完知识点下面上代码了

绘制六边形的路线

-(cgpathref)getcgpath:(cgfloat)viewwidth{
 uibezierpath * path = [uibezierpath bezierpath];
 path.linewidth = 2;
 [[uicolor whitecolor] setstroke];
 [path movetopoint:cgpointmake((sin(m_1_pi / 180 * 60)) * (viewwidth / 2), (viewwidth / 4))];
 [path addlinetopoint:cgpointmake((viewwidth / 2), 0)];
 [path addlinetopoint:cgpointmake(viewwidth - ((sin(m_1_pi / 180 * 60)) * (viewwidth / 2)), (viewwidth / 4))];
 [path addlinetopoint:cgpointmake(viewwidth - ((sin(m_1_pi / 180 * 60)) * (viewwidth / 2)), (viewwidth / 2) + (viewwidth / 4))];
 [path addlinetopoint:cgpointmake((viewwidth / 2), viewwidth)];
 [path addlinetopoint:cgpointmake((sin(m_1_pi / 180 * 60)) * (viewwidth / 2), (viewwidth / 2) + (viewwidth / 4))];
 [path closepath];
 return path.cgpath;
}

绘制一个六边形的layer,并把image 赋值到contents

 cgrect hexagnorect = self.bounds;
 //绘制一个六边形的layer,并复制一个image给他的contents
 calayer *hexagonlayer = [calayer layer];
 hexagonlayer.frame = hexagnorect;
 cashapelayer * shaplayer = [cashapelayer layer];
 shaplayer.linewidth = 1;
 shaplayer.strokecolor = [uicolor whitecolor].cgcolor;
 shaplayer.path = [self getcgpath:hexagnorect.size.width-20];
 hexagonlayer.mask = shaplayer;
 hexagonlayer.contents = (__bridge id _nullable)(self.image.cgimage);

创建一个calayer,将六边形layer 添加到calayer上,并绘制模糊阴影

 calayer *completelayer = [calayer layer];
 completelayer.frame = cgrectmake(10, 10, self.bounds.size.width-10, self.bounds.size.height-10);
 [completelayer addsublayer:hexagonlayer];
 completelayer.shadowopacity = 1.0f;
 completelayer.shadowpath = [self getcgpath:hexagnorect.size.width];
 completelayer.shadowoffset = cgsizemake(-10, -10);

 completelayer.shadowcolor = self.hg_shadowcolor.cgcolor;
 [self.layer addsublayer:completelayer];

总结

好了,以上就是在ios中实现图片六边形的全部内容了,希望本文能对大家开发ios有所帮助,如果有疑问大家可以留言交流。

上一篇:

下一篇: