一般情況下設置陰影只需要設置layer就行,但是如果只是單邊陰影番挺,只設置layer效果不是多好岩灭,可以用貝塞爾曲線實現(xiàn)。
1. 直接設置layer陰影效果
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 400, 50, 50)];
imageView.layer.shadowColor = [UIColor redColor].CGColor;
//剪切邊界 如果視圖上的子視圖layer超出視圖layer部分就截取掉 如果添加陰影這個屬性必須是NO 不然會把陰影切掉
imageView.layer.masksToBounds = NO;
//陰影半徑勋又,默認3
imageView.layer.shadowRadius = 3;
//shadowOffset陰影偏移,默認(0, -3),這個跟shadowRadius配合使用
imageView.layer.shadowOffset = CGSizeMake(0.0f,0.0f);
// 陰影透明度换帜,默認0
imageView.layer.shadowOpacity = 0.9f;
imageView.backgroundColor = [UIColor greenColor];
[self.view addSubview:imageView];
陰影效果
2. 利用貝塞爾曲線實現(xiàn)
主要代碼
- (void)viewShadowPathWithColor:(UIColor *)shadowColor shadowOpacity:(CGFloat)shadowOpacity shadowRadius:(CGFloat)shadowRadius shadowPathType:(LeShadowPathType)shadowPathType shadowPathWidth:(CGFloat)shadowPathWidth{
self.layer.masksToBounds = NO;//必須要等于NO否則會把陰影切割隱藏掉
self.layer.shadowColor = shadowColor.CGColor;// 陰影顏色
self.layer.shadowOpacity = shadowOpacity;// 陰影透明度楔壤,默認0
self.layer.shadowOffset = CGSizeZero;//shadowOffset陰影偏移,默認(0, -3),這個跟shadowRadius配合使用
self.layer.shadowRadius = shadowRadius;//陰影半徑惯驼,默認3
CGRect shadowRect = CGRectZero;
CGFloat originX,originY,sizeWith,sizeHeight;
originX = 0;
originY = 0;
sizeWith = self.bounds.size.width;
sizeHeight = self.bounds.size.height;
if (shadowPathType == LeShadowPathTop) {
shadowRect = CGRectMake(originX, originY-shadowPathWidth/2, sizeWith, shadowPathWidth);
}else if (shadowPathType == LeShadowPathBottom){
shadowRect = CGRectMake(originY, sizeHeight-shadowPathWidth/2, sizeWith, shadowPathWidth);
}else if (shadowPathType == LeShadowPathLeft){
shadowRect = CGRectMake(originX-shadowPathWidth/2, originY, shadowPathWidth, sizeHeight);
}else if (shadowPathType == LeShadowPathRight){
shadowRect = CGRectMake(sizeWith-shadowPathWidth/2, originY, shadowPathWidth, sizeHeight);
}else if (shadowPathType == LeShadowPathCommon){
shadowRect = CGRectMake(originX-shadowPathWidth/2, 2, sizeWith+shadowPathWidth, sizeHeight+shadowPathWidth/2);
}else if (shadowPathType == LeShadowPathAround){
shadowRect = CGRectMake(originX-shadowPathWidth/2, originY-shadowPathWidth/2, sizeWith+shadowPathWidth, sizeHeight+shadowPathWidth);
}
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRect:shadowRect];
self.layer.shadowPath = bezierPath.CGPath;//陰影路徑
}
陰影效果.gif