我正在使用UIGraphicsGetCurrentContext()
为 UI 元素创建渐变背景,但我想我误解了绘图的位置。我希望绘图发生在子视图上,但它发生在视图本身中。
我认为问题在于,当我使用 时UIGraphicsGetCurrentContext()
,我得到了一个CGContextRef
视图,所以这就是进行绘图的地方。我想要做的是在子视图上进行绘图,这样我就可以使用其他相关的子视图淡入淡出。可以这样做,还是我需要为背景层创建另一个 UIView 子类?
这是我正在使用的代码的简化,我的目标是能够淡入和淡出背景渐变,topBar
同时保持InterfaceControlsView
视图可见。
@implementation InterfaceControlsView
- (id)initWithFrame:(CGRect)frame
{
topBar = [[UIView alloc] initWithFrame:CGRectMake(0.0, 20.0, self.frame.size.width, 45.0)];
/* etc. */
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect rect = topBar.frame; // topBar is a subview
CGContextSaveGState(context);
CGContextAddRect(context, rect);
CGContextClip(context);
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGContextRestoreGState(context);
/* etc. */
}
@end