仅从 UIView 的 3 个侧面绘制阴影 [英] Draw shadow only from 3 sides of UIView

查看:27
本文介绍了仅从 UIView 的 3 个侧面绘制阴影的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功地实现了在我的 UIView 周围绘制阴影,如下所示:

I've successfully implemented drawing a shadow around my UIView like this:

block1.layer.masksToBounds = NO;
block1.layer.shadowOffset = CGSizeMake(0, 0);
block1.layer.shadowRadius = 1;
block1.layer.shadowOpacity = 0.7;

现在发生的是我有一个矩形 UIView 并且我想在它的三个边上绘制阴影,留下它的 底部没有 阴影.

What now happens is I have a rectangular UIView and i would like to draw the shadow around it three sides, leaving the bottom side of it without the shadow.

我知道我必须通过创建一个新的 UIBezierPath 来指定 block1.layer.shadowPath 但我不知道该怎么做.

I know that I have to specify the block1.layer.shadowPath by creating a new UIBezierPath but I'm not sure how to do it.

显然,设置 layer.shadowOffset 对我不起作用.

Obviously, setting layer.shadowOffset won't do the trick for me.

提前致谢!

推荐答案

我知道你说设置 layer.shadowOffset 对你不起作用,但是你可以输入负值所以设置它 layer.shadowOffset = CGSizeMake(0.0, -2.0) 会接近你正在寻找的效果,但当然我希望你希望它在三个方面是均匀的.

I know you say setting layer.shadowOffset won't work for you, but you are allowed to put in negative values so setting it layer.shadowOffset = CGSizeMake(0.0, -2.0) would come close to the effect you're looking for but of course I expect you want it to be even on the three sides.

所以我们使用 layer.shadowPath

UIView *block1 = [[UIView alloc] initWithFrame:CGRectMake(32.0, 32.0, 128.0, 128.0)];
[block1 setBackgroundColor:[UIColor orangeColor]];
[self.view addSubview:block1];

block1.layer.masksToBounds = NO;
block1.layer.shadowOffset = CGSizeMake(0, 0);
block1.layer.shadowRadius = 1;
block1.layer.shadowOpacity = 0.7;

UIBezierPath *path = [UIBezierPath bezierPath];

// Start at the Top Left Corner
[path moveToPoint:CGPointMake(0.0, 0.0)];

// Move to the Top Right Corner
[path addLineToPoint:CGPointMake(CGRectGetWidth(block1.frame), 0.0)];

// Move to the Bottom Right Corner
[path addLineToPoint:CGPointMake(CGRectGetWidth(block1.frame), CGRectGetHeight(block1.frame))];

// This is the extra point in the middle :) Its the secret sauce.
[path addLineToPoint:CGPointMake(CGRectGetWidth(block1.frame) / 2.0, CGRectGetHeight(block1.frame) / 2.0)];

// Move to the Bottom Left Corner
[path addLineToPoint:CGPointMake(0.0, CGRectGetHeight(block1.frame))];

// Move to the Close the Path
[path closePath];

block1.layer.shadowPath = path.CGPath;

为了让您了解发生了什么,这是您刚刚绘制的实际阴影路径:)

And to give you an idea of whats going on, here is the actual shadow path you just drew :)

可以在其他行之前或之后移动额外的中间点来选择将省略哪一侧.

Its possible to just shift that extra middle point before or after the other lines to choose which side will be omitted.

这篇关于仅从 UIView 的 3 个侧面绘制阴影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆