ios 如何根据视角动态调整阴影?

How to adjust shadow dynamically with height of view in ios?

我用圆角 corners 将阴影添加到视图中,效果很好。但是当 frame 的视图改变时 shadow 不会根据视图改变它的大小。 我尝试了以下方法:

-(void)addShadow:(UIView *)view withCornerRad : (int)radius{
    view.clipsToBounds = YES;
    CALayer *ViewLayer = view.layer;
    [ViewLayer setMasksToBounds:NO ];
    ViewLayer.shadowColor = [UIColor lightGrayColor].CGColor;
    ViewLayer.shadowOpacity = 1.0 ;
    ViewLayer.shadowRadius = 2.0 ;
    ViewLayer.shadowOffset = CGSizeMake( 0 , 0 );
    ViewLayer.cornerRadius = radius;
    ViewLayer.shadowPath = [UIBezierPath bezierPathWithRect:view.bounds].CGPath;
} 

根据Apples view programming guide

Views are responsible for drawing content, handling multitouch events, and managing the layout of any subviews.

所以你可以通过两种方式改变你的影子: 1. 通过重写 layoutSubviews 函数对 UIView 进行子类化,您可以在其中设置新的阴影大小。 2. 您可以重写控制器的 viewDidLayoutSubviews() 方法,您可以在其中设置新的阴影大小。

此致!

-(void)addShadow:(UIView *)view withCornerRad : (int)radius
{
    view.clipsToBounds = YES;
    CALayer *ViewLayer = view.layer;
    ViewLayer.shadowColor = [UIColor lightGrayColor].CGColor;
    ViewLayer.shadowRadius  = 10;
    ViewLayer.shadowOffset  = CGSizeMake(0.0f, 0.0f);
    ViewLayer.shadowOpacity = 2;
    ViewLayer.masksToBounds = NO;

    UIEdgeInsets shadowInsets     = UIEdgeInsetsMake(0, 0, 0, 0);
    UIBezierPath *shadowPath      = [UIBezierPath bezierPathWithRect:UIEdgeInsetsInsetRect(view.bounds, shadowInsets)];
    ViewLayer.shadowPath    = shadowPath.CGPath;


}

如果你想在视图的顶部、左侧、底部、右侧添加阴影,试试这个