Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a triangle UIImage

Tags:

ios

swift

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
    }
}
like image 716
shoe Avatar asked Aug 07 '26 21:08

shoe


1 Answers

Your path does not contain any lines, so there's no region to fill. In addition you are not drawing the path.

Try something like this:

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))
    //### Add lines
    ctx.addLine(to: CGPoint(x: side, y: side))
    ctx.addLine(to: CGPoint(x: 0, y: side))
    //ctx.addLine(to: CGPoint(x: side / 2, y: 0)) //### path is automatically closed
    ctx.closePath()

    ctx.setFillColor(color.cgColor)

    ctx.drawPath(using: .fill) //### draw the path

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

    return img
}
like image 153
OOPer Avatar answered Aug 09 '26 11:08

OOPer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!