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有所帮助,如果有疑问大家可以留言交流。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。