Skip to content

Instantly share code, notes, and snippets.

@rynecheow
Created October 5, 2014 04:38
Show Gist options
  • Save rynecheow/ad756f2bc8688943cbb0 to your computer and use it in GitHub Desktop.
Save rynecheow/ad756f2bc8688943cbb0 to your computer and use it in GitHub Desktop.
Create an IB live hexagonal view
//
// HexagonalView.swift
//
// Created by Ryne Cheow on 10/5/14.
// Copyright (c) 2014 Ryne Cheow. All rights reserved.
//
import UIKit
@IBDesignable
public class HexagonalView: UIView {
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
// Initialization code
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override public func prepareForInterfaceBuilder() {
setup()
}
@IBInspectable public var borderWidth: CGFloat = 0 {
didSet{
layer.borderWidth = borderWidth;
}
}
@IBInspectable public var borderColor: UIColor = UIColor.clearColor() {
didSet{
layer.borderColor = borderColor.CGColor
}
}
private func setup(){
let maskLayer = CAShapeLayer()
maskLayer.fillRule = kCAFillRuleEvenOdd
maskLayer.frame = self.bounds
let w = self.frame.size.width
let h = self.frame.size.height
let pad = w / 8 / 2
UIGraphicsBeginImageContext(self.frame.size)
let path = UIBezierPath()
path.moveToPoint(CGPointMake(w/2, 0))
path.addLineToPoint(CGPointMake(w - pad, h/4))
path.addLineToPoint(CGPointMake(w - pad, h * 3 / 4))
path.addLineToPoint(CGPointMake(w / 2, h))
path.addLineToPoint(CGPointMake(pad, h * 3 / 4))
path.addLineToPoint(CGPointMake(pad, h / 4))
path.closePath()
path.fill()
maskLayer.path = path.CGPath
UIGraphicsEndImageContext()
self.layer.mask = maskLayer }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment