Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw triangle using Core Graphics - Mac?

I want something like this: (light part, ignore background)

example triangle

How can I draw this using Cocoa? In drawRect:? I don't know how to draw.

like image 684
Names Avatar asked Jul 10 '11 03:07

Names


2 Answers

Use NSBezierPath:

- (void)drawRect:(NSRect)rect
{
    NSBezierPath *path = [NSBezierPath bezierPath];
    [path moveToPoint:NSMakePoint(0, 0)];
    [path lineToPoint:NSMakePoint(50, 100)];
    [path lineToPoint:NSMakePoint(100, 0)];
    [path closePath];
    [[NSColor redColor] set];
    [path fill];
}

This should get you started, it draws a red triangle on a 100x100 sized view. You'd usually calculate the coordinates dynamically, based on the view's size, instead of using hard-coded values of course.

like image 130
omz Avatar answered Nov 07 '22 02:11

omz


iOS + Swift

(1) Create a Swift extension

// Centered, equilateral triangle
extension UIBezierPath {
    convenience init(equilateralSide: CGFloat, center: CGPoint) {
        self.init()
        let altitude = CGFloat(sqrt(3.0) / 2.0 * equilateralSide)
        let heightToCenter = altitude / 3
        moveToPoint(CGPoint(x:center.x, y:center.y - heightToCenter*2))
        addLineToPoint(CGPoint(x:center.x + equilateralSide/2, y:center.y + heightToCenter))
        addLineToPoint(CGPoint(x:center.x - equilateralSide/2, y:center.y + heightToCenter))
        closePath()
    }
}

(2) Override drawRect

override func drawRect(rect: CGRect) {
    let path = UIBezierPath(
        equilateralSide: self.bounds.size.width,
        center: CGPoint(x: self.bounds.size.width/2, y: self.bounds.size.height/2))

    self.tintColor.set()
    path!.fill()
}
like image 44
SwiftArchitect Avatar answered Nov 07 '22 04:11

SwiftArchitect