Khledon Khledon - 2 months ago 26
iOS Question

How to round corners of UIImage with Hexagon mask

I'm trying to add a hexagon mask to a UIImage which I has been successful in. However I am unable to round the sides of the hexagon mask. I thought adding cell.profilePic.layer.cornerRadius = 10; would do the trick but it hasn't.

Here is my code:

CGRect rect = cell.profilePic.frame;

CAShapeLayer *hexagonMask = [CAShapeLayer layer];
CAShapeLayer *hexagonBorder = [CAShapeLayer layer];
hexagonBorder.frame = cell.profilePic.layer.bounds;
UIBezierPath *hexagonPath = [UIBezierPath bezierPath];
CGFloat sideWidth = 2 * ( 0.5 * rect.size.width / 2 );
CGFloat lcolumn = ( rect.size.width - sideWidth ) / 2;
CGFloat rcolumn = rect.size.width - lcolumn;
CGFloat height = 0.866025 * rect.size.height;
CGFloat y = (rect.size.height - height) / 2;
CGFloat by = rect.size.height - y;
CGFloat midy = rect.size.height / 2;
CGFloat rightmost = rect.size.width;
[hexagonPath moveToPoint:CGPointMake(lcolumn, y)];
[hexagonPath addLineToPoint:CGPointMake(rcolumn, y)];
[hexagonPath addLineToPoint:CGPointMake(rightmost, midy)];
[hexagonPath addLineToPoint:CGPointMake(rcolumn, by)];
[hexagonPath addLineToPoint:CGPointMake(lcolumn, by)];
[hexagonPath addLineToPoint:CGPointMake(0, midy)];
[hexagonPath addLineToPoint:CGPointMake(lcolumn, y)];

hexagonMask.path = hexagonPath.CGPath;
hexagonBorder.path = hexagonPath.CGPath;
hexagonBorder.fillColor = [UIColor clearColor].CGColor;
hexagonBorder.strokeColor = [UIColor blackColor].CGColor;
hexagonBorder.lineWidth = 5;
cell.profilePic.layer.mask = hexagonMask;
cell.profilePic.layer.cornerRadius = 10;
cell.profilePic.layer.masksToBounds = YES;
[cell.profilePic.layer addSublayer:hexagonBorder];


Any ideas?

Thanks

Rob Rob
Answer

You can define a path that is a hexagon with rounded corners (defining that path manually) and then apply that as the mask and border sublayer:

CGFloat lineWidth    = 5.0;
UIBezierPath *path   = [UIBezierPath roundedPolygonPathWithRect:self.imageView.bounds
                                                      lineWidth:lineWidth
                                                          sides:6
                                                   cornerRadius:30];

CAShapeLayer *mask   = [CAShapeLayer layer];
mask.path            = path.CGPath;
mask.lineWidth       = lineWidth;
mask.strokeColor     = [UIColor clearColor].CGColor;
mask.fillColor       = [UIColor whiteColor].CGColor;
self.imageView.layer.mask = mask;

CAShapeLayer *border = [CAShapeLayer layer];
border.path          = path.CGPath;
border.lineWidth     = lineWidth;
border.strokeColor   = [UIColor blackColor].CGColor;
border.fillColor     = [UIColor clearColor].CGColor;
[self.imageView.layer addSublayer:border];

Where the path of a regular polygon with rounded corners might be implemented in a category like so:

@interface UIBezierPath (Polygon)

/** Create UIBezierPath for regular polygon with rounded corners
 *
 * @param square        The CGRect of the square in which the path should be created.
 * @param lineWidth     The width of the stroke around the polygon. The polygon will be inset such that the stroke stays within the above square.
 * @param sides         How many sides to the polygon (e.g. 6=hexagon; 8=octagon, etc.).
 * @param cornerRadius  The radius to be applied when rounding the corners.
 *
 * @return              UIBezierPath of the resulting rounded polygon path.
 */

+ (instancetype)roundedPolygonPathWithRect:(CGRect)square lineWidth:(CGFloat)lineWidth sides:(NSInteger)sides cornerRadius:(CGFloat)cornerRadius;

@end

And

@implementation UIBezierPath (Polygon)

+ (instancetype)roundedPolygonPathWithRect:(CGRect)square lineWidth:(CGFloat)lineWidth sides:(NSInteger)sides cornerRadius:(CGFloat)cornerRadius {
    UIBezierPath *path  = [UIBezierPath bezierPath];

    CGFloat theta       = 2.0 * M_PI / sides;                           // how much to turn at every corner
    CGFloat offset      = cornerRadius * tanf(theta / 2.0);             // offset from which to start rounding corners
    CGFloat squareWidth = MIN(square.size.width, square.size.height);   // width of the square

    // calculate the length of the sides of the polygon

    CGFloat length      = squareWidth - lineWidth;
    if (sides % 4 != 0) {                                               // if not dealing with polygon which will be square with all sides ...
        length = length * cosf(theta / 2.0) + offset/2.0;               // ... offset it inside a circle inside the square
    }
    CGFloat sideLength = length * tanf(theta / 2.0);

    // start drawing at `point` in lower right corner

    CGPoint point = CGPointMake(squareWidth / 2.0 + sideLength / 2.0 - offset, squareWidth - (squareWidth - length) / 2.0);
    CGFloat angle = M_PI;
    [path moveToPoint:point];

    // draw the sides and rounded corners of the polygon

    for (NSInteger side = 0; side < sides; side++) {
        point = CGPointMake(point.x + (sideLength - offset * 2.0) * cosf(angle), point.y + (sideLength - offset * 2.0) * sinf(angle));
        [path addLineToPoint:point];

        CGPoint center = CGPointMake(point.x + cornerRadius * cosf(angle + M_PI_2), point.y + cornerRadius * sinf(angle + M_PI_2));
        [path addArcWithCenter:center radius:cornerRadius startAngle:angle - M_PI_2 endAngle:angle + theta - M_PI_2 clockwise:YES];

        point = path.currentPoint; // we don't have to calculate where the arc ended ... UIBezierPath did that for us
        angle += theta;
    }

    [path closePath];

    return path;
}

That yields something like so:

landscape with rounded hexagon border

Or in Swift you might do:

let lineWidth: CGFloat = 5.0;
let path = UIBezierPath(roundedPolygonPathWithRect:imageView.bounds, lineWidth: lineWidth, sides: 6, cornerRadius: 30)

let mask = CAShapeLayer()
mask.path            = path.CGPath
mask.lineWidth       = lineWidth
mask.strokeColor     = UIColor.clearColor().CGColor
mask.fillColor       = UIColor.whiteColor().CGColor
imageView.layer.mask = mask

let border = CAShapeLayer()
border.path          = path.CGPath
border.lineWidth     = lineWidth
border.strokeColor   = UIColor.blackColor().CGColor
border.fillColor     = UIColor.clearColor().CGColor
imageView.layer.addSublayer(border)

With

extension UIBezierPath {

    /// Create UIBezierPath for regular polygon with rounded corners
    ///
    /// - parameter roundedPolygonPathWithRect:  The CGRect of the square in which the path should be created.
    /// - parameter lineWidth:                   The width of the stroke around the polygon. The polygon will be inset such that the stroke stays within the above square.
    /// - parameter sides:                       How many sides to the polygon (e.g. 6=hexagon; 8=octagon, etc.).
    /// - parameter cornerRadius:                The radius to be applied when rounding the corners.

    convenience init(roundedPolygonPathWithRect rect: CGRect, lineWidth: CGFloat, sides: NSInteger, cornerRadius: CGFloat) {
        self.init()

        let theta = CGFloat(2.0 * M_PI) / CGFloat(sides)                            // how much to turn at every corner
        let offset = CGFloat(cornerRadius) * CGFloat(tan(theta / 2.0))              // offset from which to start rounding corners
        let squareWidth = min(rect.size.width, rect.size.height)          // width of the square

        // calculate the length of the sides of the polygon

        var length = squareWidth - lineWidth
        if sides % 4 != 0 {                                               // if not dealing with polygon which will be square with all sides ...
            length = length * CGFloat(cos(theta / 2.0)) + offset/2.0               // ... offset it inside a circle inside the square
        }
        let sideLength = length * CGFloat(tan(theta / 2.0))

        // start drawing at `point` in lower right corner

        var point = CGPoint(x: squareWidth / 2.0 + sideLength / 2.0 - offset, y: squareWidth - (squareWidth - length) / 2.0)
        var angle = CGFloat(M_PI)
        moveToPoint(point)

        // draw the sides and rounded corners of the polygon

        for _ in 0 ..< sides {
            point = CGPoint(x: point.x + CGFloat(sideLength - offset * 2.0) * CGFloat(cos(angle)), y: point.y + CGFloat(sideLength - offset * 2.0) * CGFloat(sin(angle)))
            addLineToPoint(point)

            let center = CGPoint(x: point.x + cornerRadius * CGFloat(cos(angle + CGFloat(M_PI_2))), y: point.y + cornerRadius * CGFloat(sin(angle + CGFloat(M_PI_2))))
            addArcWithCenter(center, radius:CGFloat(cornerRadius), startAngle:angle - CGFloat(M_PI_2), endAngle:angle + theta - CGFloat(M_PI_2), clockwise:true)

            point = currentPoint // we don't have to calculate where the arc ended ... UIBezierPath did that for us
            angle += theta
        }

        closePath()
    }

}