问题描述
我正在尝试在 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
,传递适当的值. - 执行要应用阴影的所有绘图.
- 恢复图形状态
我在 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];
}
..但这对我不起作用,我对 (a) 下一步要去哪里以及 (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);
因此,如果您希望超类的 drawRect:
被包裹"在阴影中,那么如果您像这样重新排列代码呢?
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 下绘制阴影?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!