如何在UIView下绘制阴影? [英] How do I draw a shadow under a UIView?
问题描述
我想在Cocoa Touch中的 UIView
底部画一个阴影。我理解我应该使用 CGContextSetShadow()
来绘制阴影,但Quartz 2D编程指南有点含糊:
I'm trying to draw a shadow under the bottom edge of a UIView
in Cocoa Touch. I understand that I should use CGContextSetShadow()
to draw the shadow, but the Quartz 2D programming guide is a little vague:
- 保存图形状态。
- 调用函数
CGContextSetShadow
,传递相应的值。 / li>
- 执行要应用阴影的所有绘图。
- 恢复图形状态
- Save the graphics state.
- Call the function
CGContextSetShadow
, passing the appropriate values. - Perform all the drawing to which you want to apply shadows.
- Restore the graphics state
我在 UIView
子类中尝试了以下操作:
I've tried the following in a UIView
subclass:
- (void)drawRect:(CGRect)rect {
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSaveGState(currentContext);
CGContextSetShadow(currentContext, CGSizeMake(-15, 20), 5);
CGContextRestoreGState(currentContext);
[super drawRect: rect];
}
..但这对我不起作用,我有点(b)如果我需要对我的 UIView
做任何事情,以使这项工作?
..but this doesn't work for me and I'm a bit stuck about (a) where to go next and (b) if there's anything I need to do to my UIView
to make this work?
推荐答案
在当前代码中,保存当前上下文的 GState
,配置它来绘制阴影。 。并将其还原到它是在配置它绘制阴影之前。然后,最后,你调用超类的实现 drawRect
:
In your current code, you save the GState
of the current context, configure it to draw a shadow .. and the restore it to what it was before you configured it to draw a shadow. Then, finally, you invoke the superclass's implementation of drawRect
: .
任何应该受阴影影响的图形设置需要在之后
Any drawing that should be affected by the shadow setting needs to happen after
CGContextSetShadow(currentContext, CGSizeMake(-15, 20), 5);
但之前
CGContextRestoreGState(currentContext);
<
So if you want the superclass's drawRect:
to be 'wrapped' in a shadow, then how about if you rearrange your code like this?
- (void)drawRect:(CGRect)rect {
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSaveGState(currentContext);
CGContextSetShadow(currentContext, CGSizeMake(-15, 20), 5);
[super drawRect: rect];
CGContextRestoreGState(currentContext);
}
这篇关于如何在UIView下绘制阴影?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!