你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS實現圖片六邊形陰影效果

iOS實現圖片六邊形陰影效果

編輯: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有所幫助,如果有疑問大家可以留言交流。

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved