user007
user007

Reputation: 69

Gradient Color to Custom View

I have created 3 custom views in a UIViewController. In each custom view, I have created shapes using CAShapeLayer.

These layers also contain gradient colour. Now I want to set gradient colour to custom views. When I am trying to do that, it is crashing. For first view, here is code :

//first component
    self.aTimeScaleMonthView = [[TimeScaleView alloc] initWithFrame:CGRectMake(ORIGIN_X, frame.origin.y, frame.size.width-(2*ORIGIN_X), HEIGHT_OF_COMPONENT1) withStartDate:startDate endDate:endDate];
    self.aTimeScaleMonthView.modeOfScale = A3TimeScaleMonth;
    self.aTimeScaleMonthView.layer.borderColor = [UIColor blackColor].CGColor;
    self.aTimeScaleMonthView.layer.borderWidth = BORDER_WIDTH_BOX;

    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = self.aTimeScaleMonthView.bounds;
    gradient.colors = [NSArray arrayWithObjects:[UIColor colorWithRed:0.66 green:0.29 blue:0.22 alpha:1.0], [UIColor colorWithRed:0.62 green:0.51 blue:0.314 alpha:1.0], nil];

    [self.aTimeScaleMonthView.layer insertSublayer:gradient atIndex:0];
    [self addSubview: self.aTimeScaleMonthView];

Please help me.

Upvotes: 0

Views: 296

Answers (2)

james_womack
james_womack

Reputation: 10296

CALayer and its subclasses take CGColor, not UIColor. You can transmute a UIColor to the Core Graphics color struct CGColor by accessing the CGColor property of UIColor instances.

Also important to understand: CoreFoundation structures & those of related C APIs such as CoreGraphics (anything starting with CG is CoreGraphics related) cannot be inserted into NSArray straight out because they are not object-oriented. You must cast the structure to id to place it inside an NSArray instance. You cast in Objective-C using parens around the type you wish to cast to. In this case you would do the following:

gradient.colors = @[(id)[UIColor colorWithRed:0.66 green:0.29 blue:0.22 alpha:1.0].CGColor, (id)[UIColor colorWithRed:0.62 green:0.51 blue:0.314 alpha:1.0].CGColor];

To make your code more readable and your colors reusable, you should assign the colors to descriptive variables and add those variables into the NSArray in their place.

You do not need to set the startPoint and endPoint if a straight up and down gradient is what you want. That is the most common desired configuration and is accordingly the default. Also, using object literal syntax for array creation is preferred today over @selector(arrayWithObjects:).

Don't forget to set the layerClass class method of your custom UIView subclass.

Upvotes: 0

Kyr Dunenkoff
Kyr Dunenkoff

Reputation: 8090

Gradient colors should be CGColor: gradient.colors = [NSArray arrayWithObjects:(id)[UIColor colorWithRed:0.66 green:0.29 blue:0.22 alpha:1.0].CGColor, (id)[UIColor colorWithRed:0.62 green:0.51 blue:0.314 alpha:1.0].CGColor, nil];

Btw, you forgot to set start and end points for your gradient.

Upvotes: 2

Related Questions