Search code examples
iphoneobjective-ccocoa-touchuiviewcglayer

Issue in adding a shadow to view layer


In one of my view I am adding shadow to a view. Thing is that the shadow shows white spaces on left & right edges. I want to remove these spaces.

Here is my code:

UIView *myView = [[ISTView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 35)];
myView.backgroundColor = [UIColor greyColor];
[myView.layer setShadowOffset:CGSizeMake(0.0, 5.0)];
[myView.layer setShadowOpacity:0.8];
[myView.layer setShadowRadius:2.0];
[myView.layer setShadowColor:[UIColor blackColor].CGColor];
[self.view addSubview:myView];
[myView release];

Here is my view's o/p:

enter image description here


Solution

  • If you want homogenous shadow without side effects you can draw it in graphics editor, save to png and place UIImageView with stretchable image on your view. And don't forget to set clipToBounds to NO.

    UIView *myView = [[ISTView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 35)];
    myView.backgroundColor = [UIColor greyColor];
    myView.clipToBounds = NO;
    
    UIImageView *shadowView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 35, 320, 10)];
    shadowView.image = [UIImage imageWithName:@"my-shadow.png"];
    [myView addSubview:shadowView];
    [shadowView release];
    
    [self.view addSubview:myView];
    [myView release];
    

    It would be cheaper for system to draw cached existing image above view hierarcy than calculate layer's shadow.