0

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

1 回答 1

2

要为子视图创建渐变背景,您不需要创建子类,使用渐变层。希望这可以帮助

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];
于 2012-11-23T11:30:01.670 回答