How to make CALayer border with Gradient or Multip

2019-09-05 18:29发布

问题:

        CALayer *rightBorder = [CALayer layer];
        rightBorder.borderColor = [UIColor redColor].CGColor;
        rightBorder.borderWidth = 1;
        rightBorder.frame = CGRectMake(-1, -1, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame)+2);

        [self.layer addSublayer:rightBorder];

I am making border of a WebView like above. here self is inherited from UIWebView.

How can I change

rightBorder.borderColor = [UIColor redColor].CGColor;

to a Gradient color, so half of my color should be blue, and half white.

Here, I am applying on RED color to border of my WebView. However I want a multicolor (2 color) or gradient.

Thanks.

回答1:

To show different color in one layer with gradient effect i am sharing one method of my code you have to use CAGradientLayer for that,

-(void)addGradiantColor:(UIView *)view;
{
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = view.frame;
     //  gradientLayer.startPoint = CGPointMake(0.0,0.0);
     //  gradientLayer.endPoint = CGPointMake(1.0,1.0);
    NSMutableArray *colors = [NSMutableArray array];
    [colors addObject:(id)[[UIColor colorWithRed:134.0/255.0 green: 234.0/255.0   blue:63.0/255.0 alpha:1.0] CGColor]];
    [colors addObject:(id)[[UIColor colorWithRed:215.0/255.0 green: 82.0/255.0 blue:76.0/255.0 alpha:1.0] CGColor]];
    gradientLayer.colors = colors;
    [view.layer addSublayer:gradientLayer];   
}