【问题标题】:How to adjust shadow dynamically with height of view in ios?如何在ios中使用视图高度动态调整阴影?
【发布时间】:2016-10-16 12:56:06
【问题描述】:

我用圆角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;
} 

【问题讨论】:

  • 每次更改视图框架时都必须更新视图阴影

标签: ios dynamic uiview shadow rounded-corners


【解决方案1】:

Apples view programming guide

视图负责绘制内容、处理多点触控事件以及管理任何子视图的布局。

因此,您可以通过两种方式更改阴影: 1. 通过使用覆盖 layoutSubviews 函数的 UIView 子类化,您可以在其中设置新的阴影大小。 2. 你可以覆盖你的控制器 viewDidLayoutSubviews() 方法,在这里你可以设置新的阴影大小。

最好的问候!

【讨论】:

  • 在此解决方案中,每次都会重绘阴影。我也喜欢通过添加观察者来重绘阴影的解决方案。 self.container.addObserver(self, forKeyPath: "bounds", options: NSKeyValueObservingOptions.init(rawValue: 0) , context: nil)
  • 有没有自动处理阴影大小的解决方案?
  • -(void) viewDidLayoutSubview { [super viewDidLayoutSubviews]; [self addShadow:self.youView with CornerRad:5.0]; }
【解决方案2】:
-(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;


}

如果您想要阴影顶部、左侧、底部、右侧视图,请尝试此操作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多