代码:
ViewController.h
#import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
ViewController.m
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UIView *view = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)]; [self.view addSubview:view]; //添加View的阴影 [self addShadowWithView:view]; //[self addShadowWithView2:view]; } //添加View的阴影 - (void)addShadowWithView:(UIView *)view{ view.layer.shadowColor = [UIColor blackColor].CGColor;//shadowColor阴影颜色,默认为黑色 view.layer.shadowOffset = CGSizeMake(4, 4); view.layer.shadowOpacity = 1.0; view.layer.shadowRadius = 3; //路径阴影 UIBezierPath *path = [UIBezierPath bezierPath]; float width = view.bounds.size.width; float height = view.bounds.size.height; float x = view.bounds.origin.x; float y = view.bounds.origin.y; CGPoint topLeft = CGPointMake(x, y); CGPoint topMiddle = CGPointMake(x + (width/2), y); CGPoint topRight = CGPointMake(x + width, y); CGPoint rightMiddle = CGPointMake(x + width, y + (height/2)); CGPoint bottomRight = CGPointMake(x+width, y+height); CGPoint bottomMiddle = CGPointMake(x + (width/2), y + height); CGPoint bottomLeft = CGPointMake(x, y + height); CGPoint leftMiddle = CGPointMake(x, 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]; view.layer.shadowPath = path.CGPath; } //添加View的阴影2 - (void)addShadowWithView2:(UIView *)view{ //使用这种办法来设置投影,必须添加背景颜色或者边框颜色否则是无法显示的 view.layer.borderColor = [UIColor blueColor].CGColor; view.layer.borderWidth = 1.0; view.layer.shadowColor = [UIColor blackColor].CGColor; view.layer.shadowOffset = CGSizeMake(4, 4); view.layer.shadowOpacity = 1.0; view.layer.shadowRadius = 2; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
实例代码:
参考链接: