-2

Is it possible create an UIImage or an UIImageView with hexagonal corners? Because I want take an UIImage and show it inside an UIImageView but inside and hexagon. Thanks

dandan78
  • 13,328
  • 13
  • 64
  • 78
Luca
  • 770
  • 8
  • 25
  • Maybe this can help you http://stackoverflow.com/questions/19723533/how-to-draw-hexagon-using-cgmutablepathref-in-ios – user2432612 Nov 21 '14 at 13:54
  • you can use this library https://github.com/mattgemmell/MGImageUtilities – Eddwin Paz Nov 21 '14 at 14:16
  • 1
    yes, everything is possible. – holex Nov 21 '14 at 15:28
  • @holex, of course but how? – Luca Nov 21 '14 at 15:30
  • 1
    you can create a subset of the `UIImageView`, and you can override the `–drawRect:` method, e.g. masking the actual content with a regular hexagon, which hexagon mask you could create using _CoreGraphics.framework_. piece of cake. – holex Nov 21 '14 at 15:36

1 Answers1

5

After a while I found a simple implementation. I created an hexagonal view:

HexagonView.h

#import <UIKit/UIKit.h>

@interface HexagonView : UIView
@end

HexagonView.m

#import "HexagonView.h"
#import <QuartzCore/QuartzCore.h>

@implementation HexagonView

- (void)drawRect:(CGRect)rect {

    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.fillRule = kCAFillRuleEvenOdd;
    maskLayer.frame = self.bounds;

    CGFloat width = self.frame.size.width;
    CGFloat height = self.frame.size.height;
    CGFloat hPadding = width * 1 / 8 / 2;

    UIGraphicsBeginImageContext(self.frame.size);
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(width/2, 0)];
    [path addLineToPoint:CGPointMake(width - hPadding, height / 4)];
    [path addLineToPoint:CGPointMake(width - hPadding, height * 3 / 4)];
    [path addLineToPoint:CGPointMake(width / 2, height)];
    [path addLineToPoint:CGPointMake(hPadding, height * 3 / 4)];
    [path addLineToPoint:CGPointMake(hPadding, height / 4)];
    [path closePath];
    [path closePath];
    [path fill];
    [path stroke];

    maskLayer.path = path.CGPath;

    UIGraphicsEndImageContext();

    self.layer.mask = maskLayer;

}

@end

Then I add as subview my ImageView on HexagonView:

[hexagonView addSubview:scaledImageView];

And the result is this: enter image description here

Luca
  • 770
  • 8
  • 25