penatheboss penatheboss - 7 months ago 82
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:

diamond

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

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
Comments