apply clear color in CALayer

1.4k views Asked by At

How to apply in clear color in this circular UIView in the region covered in green, or the white color in the center will be faded from the center.

enter image description here

Here is the code:-

   UIView *vwx=[[UIView alloc]initWithFrame:CGRectMake(150, self.view.frame.size.height/2, 100, 100)];

    vwx.layer.cornerRadius = 50;
    vwx.layer.masksToBounds = YES;
    CircleGradient *gradientLayer = [CircleGradient new];
    gradientLayer.frame = vwx.bounds;

    [vwx.layer addSublayer:gradientLayer];
    [self.view addSubview:vwx];

This is what I have done in sub-classing CALayer

- (void)drawInContext:(CGContextRef)ctx
{

    size_t gradLocationsNum = 2;
    CGFloat gradLocations[2] = {0.0f, 1.0f};
    CGFloat gradColors[3] = {0.0f,0.0f,0.0f};
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, gradColors, gradLocations, gradLocationsNum);
    CGColorSpaceRelease(colorSpace);

    CGPoint gradCenter= CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
    float gradRadius = MIN(self.bounds.size.width , self.bounds.size.height) ;

    CGContextDrawRadialGradient (ctx, gradient, gradCenter, 0, gradCenter, gradRadius, kCGGradientDrawsAfterEndLocation);


    CGGradientRelease(gradient);
}

Any help or suggestion will be helpful

2

There are 2 answers

2
iAnurag On

Try this code. did solve with this

int radius = myRect.size.width;
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0,  0, self.mapView.bounds.size.width, self.mapView.bounds.size.height) cornerRadius:0];
UIBezierPath *circlePath = [UIBezierPath  bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius) cornerRadius:radius];
[path appendPath:circlePath];
[path setUsesEvenOddFillRule:YES];

CAShapeLayer *fillLayer = [CAShapeLayer layer];
fillLayer.path = path.CGPath;
fillLayer.fillRule = kCAFillRuleEvenOdd;
fillLayer.fillColor = [UIColor grayColor].CGColor;
fillLayer.opacity = 0.5;
[view.layer addSublayer:fillLayer];
0
Jay Bhalani On

By setting your circular UIView's background color to [[UIColor clearColor] CGColor]; you'll achieve a transparent (clear) view.