iosiphoneimage-processingcgcontextrefcgcontextdrawimage

How to clear circle in CGContext in iOS


I want create image using CGcontext. This is simple image with white or black background. also I want to add transperent part which is in circle ( check attached image). I know how to do this in rect. But i want to make it circle. Please anyone help me in this. enter image description here


Solution

  • Use the below code to clear circle in your context

    -(UIImage *) getImageWithcenterClear:(CGPoint) center{
    
        CGRect frame = [[UIScreen mainScreen] bounds];
    
        UIGraphicsBeginImageContextWithOptions([[UIScreen mainScreen] bounds].size,
                                           NO, [UIScreen mainScreen].scale);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5 ] CGColor]);
        CGContextFillRect(context, frame);
    
        float radius = 50 * 2;
        // Clear Circle
    
        CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
        CGContextSetBlendMode(context, kCGBlendModeClear);
        CGContextAddArc(context, center.x, center.y, radius - 0.54, 0, 2 * M_PI, 0);
        CGContextDrawPath(context, kCGPathFill);
        CGContextSetBlendMode(context, kCGBlendModeNormal);
    
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return image;
    
    }