iOS实现图片六边形阴影效果
程序员文章站
2023-12-19 10:39:10
先来看看效果图
这个效果写起来挺简单,主要运用下面几个知识点
layer 的mask : 图层蒙版
...
先来看看效果图
这个效果写起来挺简单,主要运用下面几个知识点
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有所帮助,如果有疑问大家可以留言交流。