Create inner shadow in UIView [duplicate]

ぃ、小莉子 提交于 2020-01-28 20:08:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!