【问题标题】:How to make a UIView shadow stretch when device is rotated?设备旋转时如何使 UIView 阴影拉伸?
【发布时间】:2019-03-22 02:57:45
【问题描述】:

在自定义表格视图单元格中,我正在绘制一个带有阴影的简单矩形,如下所示:

photoBorder = [[[UIView alloc] initWithFrame:CGRectMake(4, 4, self.frame.size.width-8, 190)] autorelease];
photoBorder.autoresizingMask = UIViewAutoresizingFlexibleWidth;
photoBorder.backgroundColor = [UIColor whiteColor];
photoBorder.layer.masksToBounds = NO;
photoBorder.layer.shadowOffset = CGSizeMake(0, 1);
photoBorder.layer.shadowRadius = 4;
photoBorder.layer.shadowOpacity = 1.0;
photoBorder.layer.shadowColor = [UIColor darkGrayColor].CGColor;
photoBorder.layer.shouldRasterize = YES;
photoBorder.layer.shadowPath = [UIBezierPath bezierPathWithRect:photoBorder.bounds].CGPath; // this line seems to be causing the problem

当视图首次加载时,这可以正常工作。但是,当您旋转设备时,阴影保持不变。我真的很想把它拉伸到“photoBorder”的新宽度。

我可以通过删除 shadowPath 来使其工作,但 tableview 的性能会受到明显影响。

谁有关于在 UIView 上制作可以拉伸而不会损失性能的阴影的技巧?

【问题讨论】:

    标签: ios uiview shadow autoresizingmask


    【解决方案1】:

    在搜索了几个小时并没有找到任何东西后,我发布了这个。然后在几分钟后找到了答案。

    对我来说,简单的解决方案似乎只是将 shadowPath 移动到 layoutSubviews 中。

    - (void)layoutSubviews{
        photoBorder.layer.shadowPath = [UIBezierPath bezierPathWithRect:photoBorder.bounds].CGPath;
    }
    

    【讨论】:

      【解决方案2】:

      您需要创建一个 UIView 的子类,以便您可以在 layoutSubviews() 方法中获取新的边界。

      注意:如果您尝试在拥有子视图的 ViewController 中添加此代码,则边界将在您旋转时保持静态,这会导致 shadowPath 错误。

      import UIKit
      
      class BackgroundView: UIView {
      
          required init?(coder aDecoder: NSCoder) {
              super.init(coder: aDecoder)
          }
      
          override func layoutSubviews() {
              super.layoutSubviews()
              updateShadow(on: self)
          }
      
          func updateShadow(on background: UIView) {
              let layer = background.layer
              layer.shadowPath = UIBezierPath(rect: background.bounds).cgPath
              layer.masksToBounds = false
              layer.shadowColor = UIColor.black.cgColor
              layer.shadowOffset = CGSize(width: 0, height: 2)
              layer.shadowRadius = 4
              layer.shadowOpacity = 0.22
          }
      
      }
      
      1. 确保调用 super.layoutSubviews() 来处理任何自动布局约束。

      2. 您可以在 Storyboard 文件中设置自定义类。

      【讨论】:

        【解决方案3】:

        为了提高性能,您可以使用 Core Graphics 绘制内部阴影。

        Inner shadow effect on UIView layer

        【讨论】:

          猜你喜欢
          • 2011-08-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-21
          • 2021-02-09
          • 1970-01-01
          • 1970-01-01
          • 2017-09-02
          相关资源
          最近更新 更多