【问题标题】:making drop shadows on UIViews在 UIViews 上制作阴影
【发布时间】:2014-02-10 02:24:24
【问题描述】:

我在自定义的 UIView 初始化中使用此代码:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        ...

        UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:CGRectMake(frame.origin.x, frame.size.height, frame.size.width, 15)];
        self.layer.masksToBounds = NO;
        self.layer.shadowColor = [UIColor blackColor].CGColor;
        self.layer.shadowOffset = CGSizeMake(0.0f, 4.0f);
        self.layer.shadowOpacity = 0.5f;
        self.layer.shadowPath = shadowPath.CGPath;
    }
    return self;
}

尝试制作这样的阴影:

1)

但我得到了这个效果:

2)

您可以看到这是我想要实现的颠倒版本。如何制作第一张图片的阴影效果?

【问题讨论】:

  • 为什么你不这样做 UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:view.bounds];
  • 这条线将在整个视图上投下阴影。我只想让阴影出现在 UIView 的底部。

标签: ios uiview shadow


【解决方案1】:

问题在于您的shadowPath

使用CGRectMake(frame.origin.x, frame.size.height, frame.size.width, 15) 创建您的UIBezierPath 将设置不正确的原点。

首先,origin.x 应该是0.0f,否则如果您的UIVieworigin.x != 0.0f,阴影会移得很远。其次,您需要将shadowPath 的底部与UIView 的底部对齐。

这是UIViews 的屏幕截图,使用您的影子代码说明了这些问题。 (在下方的UIView 中,您看不到阴影,因为它远离屏幕右侧)。

如果您将 rect 更改为:

const CGFloat shadowRectHeight = 15.0f;
CGRect shadowRect = CGRectMake(0.0f, self.bounds.size.height - shadowRectHeight, self.bounds.size.width, shadowRectHeight)];

【讨论】:

  • 谢谢。虽然主要问题是我的自定义 uiview 位于其父视图的底部,因此其他视图与其阴影重叠,但我认为这个答案非常有帮助并节省了我一些时间。
【解决方案2】:

这样做并设置UIView alpha

CAGradientLayer *gradient = [CAGradientLayer layer];  
gradient.frame = rect;  
gradient.colors = [NSArray arrayWithObjects:(id)[UIColor blackColor].CGColor,   
                                            (id)[UIColor grayColor].CGColor,   
                                            (id)[UIColor blackColor].CGColor,nil];  
[self.layer insertSublayer:gradient atIndex:0];  

您可以添加或删除要显示的 UIColor。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 2013-06-08
    • 2018-04-17
    • 1970-01-01
    相关资源
    最近更新 更多