Search code examples
iosmathuiimagecurve

Transparent Pixels on bottom corners of UIImage?


I am trying to make my image transparent on corners at the bottom so as to support a face curved look. I have tried with the following code but CGPathAddArc is a bit confusing as I am not much of a math bluff. Red corners as shown in image defines the area I want to make transparent

What I have

Red line shape I want to make transparent

UIGraphicsBeginImageContext(originalImage.size);
[originalImage drawAtPoint:CGPointZero];

CGMutablePathRef testRef = CGPathCreateMutable();
//CGAffineTransform temp = CGAffineTransformMakeRotation(M_PI / 2);
//CGPathAddEllipseInRect(testRef, &temp, CGRectMake(0,0,20,20));
//CGPathAddQuadCurveToPoint(testRef, nil, 20,20, 150, 150);
//CGPathAddCurveToPoint(testRef, NULL, 20, 20, 40, 40, 100, 100);

CGPathMoveToPoint(testRef, NULL, 20, 20);
CGPathAddArc(testRef, NULL, 0, 15, 15, M_PI_2, -M_PI_2, true);

// Clip to the path and clear that portion of the image.
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextAddPath(context,testRef);
CGContextClip(context);
CGContextClearRect(context,CGRectMake(0,0,originalImage.size.width,originalImage.size.height));
    // Build a new UIImage from the image context.
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

Solution

  • if you are not that familiar with core-foundation and low level stuff, you can simple use [UIBezierPath bezierPathWithRoundedRect:byRoundingCorners:cornerRadii:] to get a Rectangle with rounded corners.

    Example:

        UIGraphicsBeginImageContext(originalImage.size);
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, originalImage.size.width, originalImage.size.height)
                                                   byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight
                                                         cornerRadii:CGSizeMake(15, 15)];
        [path addClip];
        [originalImage drawAtPoint:CGPointZero];
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();