效果圖如下:
直接貼代碼吧:
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIView *normalView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//四邊都出現(xiàn)陰影的效果(shadowPath 用法)
[self allShadow];
//普通的用法
[self normalUser];
}
//四邊陰影(shadowPath 用法)
- (void)allShadow {
_contentView = [[UIView alloc] initWithFrame:CGRectMake(30, 50, 200, 200)];
_contentView.backgroundColor = [UIColor redColor];
[self.view addSubview:_contentView];
//shadowColor陰影顏色
_contentView.layer.shadowColor = [UIColor blueColor].CGColor;
//shadowOffset陰影偏移宴凉,默認(0, -3),這個跟shadowRadius配合使用
_contentView.layer.shadowOffset = CGSizeMake(0,0);
//陰影透明度誊锭,默認0
_contentView.layer.shadowOpacity = 1;
//陰影半徑,默認3
_contentView.layer.shadowRadius = 10;
//路徑陰影(借助貝塞爾曲線)
UIBezierPath *path = [UIBezierPath bezierPath];
float width = _contentView.bounds.size.width;
float height = _contentView.bounds.size.height;
float x = _contentView.bounds.origin.x;
float y = _contentView.bounds.origin.y;
float addWH = 10;
CGPoint topLeft = _contentView.bounds.origin;
CGPoint topMiddle = CGPointMake(x+(width/2),y-addWH);
CGPoint topRight = CGPointMake(x+width,y);
CGPoint rightMiddle = CGPointMake(x+width+addWH,y+(height/2));
CGPoint bottomRight = CGPointMake(x+width,y+height);
CGPoint bottomMiddle = CGPointMake(x+(width/2),y+height+addWH);
CGPoint bottomLeft = CGPointMake(x,y+height);
CGPoint leftMiddle = CGPointMake(x-addWH,y+(height/2));
[path moveToPoint:topLeft];
//添加四個二元曲線
[path addQuadCurveToPoint:topRight
controlPoint:topMiddle];
[path addQuadCurveToPoint:bottomRight
controlPoint:rightMiddle];
[path addQuadCurveToPoint:bottomLeft
controlPoint:bottomMiddle];
[path addQuadCurveToPoint:topLeft
controlPoint:leftMiddle];
//設置陰影路徑
_contentView.layer.shadowPath = path.CGPath;
}
//基礎用法
- (void)normalUser {
_normalView = [[UIView alloc] initWithFrame:CGRectMake(30, 350, 200, 200)];
_normalView.backgroundColor = [UIColor orangeColor];
[self.view addSubview:_normalView];
//設置陰影顏色
_normalView.layer.shadowColor = [UIColor blackColor].CGColor;
//設置陰影的半徑
_normalView.layer.shadowRadius = 5;
//設置陰影的透明度
_normalView.layer.shadowOpacity = 1.0;
//設置陰影在bounds中的偏移量
_normalView.layer.shadowOffset = CGSizeMake(10, 10);
}