How to create a triangle UIImage

Viewed 704

How can I create a triangle UIImage? Here's how I'm doing it now, but it's not producing any image at all.

extension UIImage {

    static func triangle(side: CGFloat, color: UIColor)->UIImage {
        UIGraphicsBeginImageContextWithOptions(CGSize(width: side, height: side), false, 0)
        let ctx = UIGraphicsGetCurrentContext()!
        ctx.saveGState()

        ctx.beginPath()
        ctx.move(to: CGPoint(x: side / 2, y: 0))
        ctx.move(to: CGPoint(x: side, y: side))
        ctx.move(to: CGPoint(x: 0, y: side))
        ctx.move(to: CGPoint(x: side / 2, y: 0))
        ctx.closePath()

        ctx.setFillColor(color.cgColor)

        ctx.restoreGState()
        let img = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        return img
    }
}
3 Answers
Related