Iphone 从子视图获取CGContextRef

Iphone 从子视图获取CGContextRef,iphone,uiview,cgcontextref,Iphone,Uiview,Cgcontextref,我正在使用UIGraphicsGetCurrentContext()为UI元素创建渐变背景,但我想我误解了绘图的位置。我希望绘图发生在子视图上,但它发生在视图本身中 我认为问题在于,当我使用UIGraphicsGetCurrentContext()时,我得到的是视图的CGContextRef,因此这就是绘图的地方。我想做的是让绘图在子视图上进行,这样我就可以在其他相关子视图中淡入淡出。这可以做到吗,或者我需要为背景层创建另一个UIView子类吗 这里是我正在使用的代码的简化,我的目标是能够淡入淡

我正在使用
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

要为子视图创建渐变bg,不需要创建子类,请使用渐变层。 希望这有帮助

CALayer *layer = _button.layer;
layer.borderWidth = 1.0f;
layer.borderColor = [UIColor lightGrayColor].CGColor;


CAGradientLayer *gLayer = [CAGradientLayer layer];
[gLayer setName:@"gradient"];

gLayer.frame = layer.bounds;

gLayer.colors = [NSArray arrayWithObjects:
                         (id)[UIColor colorWithRed:26.0/255.0 green:94.0/255.0 blue:74.0/255.0 alpha:1.0].CGColor,
                         (id)[UIColor colorWithRed:23.0/255.0 green:59.0/255.0 blue:37.0/255.0 alpha:1.0].CGColor,
                         nil];
[layer addSublayer:gLayer];

谢谢比我做的容易多了。非常感谢。