0

I'm using UIGraphicsGetCurrentContext() to create a gradient background for a UI element, but I guess I misunderstood where the drawing was taking place. I wanted the drawing to take place on a subview, but instead it's happening in the view itself.

I think the problem is that when I use UIGraphicsGetCurrentContext(), I'm getting a CGContextRef of the view, so that's where the drawing is taking place. What I want to do is have the drawing take place on the subview, so that I can fade it in and out with other related subviews. Can this be done, or do I need to create another UIView subclass just for the background layer?

Here's a simplification of the code I'm using and my goal is to be able to fade in and out the background gradient in topBar while leaving the InterfaceControlsView view visible.

@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
Andrew
  • 14,204
  • 15
  • 60
  • 104

1 Answers1

2

To create gradient bg for subviews, you dont need to create subclass, use gradiant layers. Hope this helps

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];
DivineDesert
  • 6,924
  • 1
  • 29
  • 61