penatheboss penatheboss - 1 year ago 176
Swift Question

Diamond-like UIView

I am trying to create a UIView with corners like a shape of a diamond, as shown in the picture:


I am familiar with rounding off corners:

myView.layer.cornerRadius = 10

However, I want a different shape. How could I create this effect? Thanks for your help!

Answer Source

Best way to solve a problem like this is by using CAShapeLayer. Here's the kind of thing that would work: paste it into a playground and see how it clips off the corners.

import UIKit
import XCPlayground

let diamond = UIView(frame: CGRect(x:0, y: 0, width: 100, height:100))
diamond.backgroundColor = UIColor.redColor()
XCPlaygroundPage.currentPage.liveView = diamond

let path = UIBezierPath()
path.moveToPoint(CGPoint(x: 20,y: 0))
path.addLineToPoint(CGPoint(x: 80,y: 0))
path.addLineToPoint(CGPoint(x: 80,y: 0))
path.addLineToPoint(CGPoint(x: 100,y: 20))
path.addLineToPoint(CGPoint(x: 100,y: 80))
path.addLineToPoint(CGPoint(x: 80,y: 100))
path.addLineToPoint(CGPoint(x: 20,y: 100))
path.addLineToPoint(CGPoint(x: 0,y: 80))
path.addLineToPoint(CGPoint(x: 0,y: 20))
path.addLineToPoint(CGPoint(x: 20,y: 0))

let mask = CAShapeLayer()
mask.frame = diamond.bounds
mask.path = path.CGPath
diamond.layer.mask = mask