Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create inner shadow in UIView [duplicate]

I would like create an inner shadow on my UIView on iPad like that :

UIView with shadow

This UIView could change size so I can't use a simple image to create this kind of shadow.

I have tested with setShadow etc., but it's only a dropshadow that is created.

Any idea how to create this kind of shadow?

like image 384
alexmngn Avatar asked Feb 09 '12 16:02

alexmngn


2 Answers

You may find it useful, I made an UIView Category for that

https://github.com/Seitk/UIView-Shadow-Maker

like image 62
Seitk Avatar answered Sep 27 '22 23:09

Seitk


Create the shadow as a transparent layer at a particular size, then create a stretchable image, like this:

UIImage *shadowImage = [UIImage imageNamed:@"shadow.png"];
shadowImage = [shadowImage stretchableImageWithLeftCapWidth:floorf(shadowImage.size.width/2) topCapHeight:floorf(shadowImage.size.height/2)];

You can then put that as the image in a UIImageView with contentMode scale to fit and it will work the way you want.

Lets say your view is called "myView". You can add the shadow like this:

UIImageView *shadowImageView = [[UIImageView alloc] initWithImage:shadowImage];
shadowImageView.contentMode = UIViewContentModeScaleToFill;
shadowImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
shadowImageView.frame = myView.bounds;
[myView addSubview:shadowImageView];
[shadowImageView release]; // only needed if you aren't using ARC

You can also do most of this in interface builder if you prefer, as long as you create the stretchable image itself in code.

like image 26
Nick Lockwood Avatar answered Sep 27 '22 22:09

Nick Lockwood