Pregunta

I use this code in my customized UIView initialization:

- (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;
}

trying to make a drop shadow like this:

1)

enter image description here

But I got this effect:

2)

enter image description here

You can see this is an upside down version of what I want to achieve. How to make the shadow effect of the first image?

¿Fue útil?

Solución

The issue is just with your shadowPath.

Using CGRectMake(frame.origin.x, frame.size.height, frame.size.width, 15) to create your UIBezierPath will set an incorrect origin.

First, origin.x should be 0.0f or the shadow will shift far away if your UIView's origin.x != 0.0f. Second, you need to line up the bottom of the shadowPath with the bottom of your UIView.

This is a screenshot of UIViews using your shadow code illustrating these issues. (In the lower UIView you cannot see the shadow because it is far off the right of the screen).
Screenshot with incorrect shadowPath

You will see what you intended if you change the rect to:

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

Screenshot with correct shadowPath

Otros consejos

Do like this and set the 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];  

you can add or remove UIColor you want to display.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top