问题
I would like create an inner shadow on my UIView
on iPad like that :
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?
回答1:
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.
回答2:
You may find it useful, I made an UIView Category for that
https://github.com/Seitk/UIView-Shadow-Maker
回答3:
This question was already partially answered in SO
view.layer.masksToBounds = NO;
view.layer.cornerRadius = 8; // if you like rounded corners
view.layer.shadowRadius = 5;
view.layer.shadowOpacity = 0.5;
CGFloat indent = 10;
CGRect innerRect = CGRectMake(indent,indent,view.frame.size.width-2*indent,view.frame.size.height-2*indent);
view.layer.shadowPath = [UIBezierPath bezierPathWithRect:innerRect].CGPath;
Play around with the variables until they suit your shadow style.
UPDATE
Instead you can draw an outer shadow on a smaller centered view which lies on top of your existing view.
CGFloat indent = 10;
CGRect innerRect = CGRectMake(indent,indent,view.frame.size.width-2*indent,view.frame.size.height-2*indent);
UIView * shadowView = [[UIView alloc] initWithFrame:innerRect];
shadowView.backgroundColor = [UIColor clearColor];
shadowView.layer.masksToBounds = NO;
shadowView.layer.cornerRadius = 8; // if you like rounded corners
shadowView.layer.shadowRadius = 5;
shadowView.layer.shadowOpacity = 0.5;
shadowView.layer.shadowPath = [UIBezierPath bezierPathWithRect:shadowView.bounds].CGPath;
[view addSubview:shadowView];
[shadowView release];
来源:https://stackoverflow.com/questions/9214482/create-inner-shadow-in-uiview