Names
Names

Reputation: 53

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.

Upvotes: 5

Views: 10144

Answers (3)

John Robi
John Robi

Reputation: 345

iOS + Swift5 (Updated Context handling, allow for diff widths)

        let triangleWidth: CGFloat = 8.0
        let heightToCenter: CGFloat = 4.0 // This controls how "narrow" the triangle is
        let center: CGPoint = centerPoint
        context.setFillColor(UIColor.red.cgColor)
        context.move(to: CGPoint(x:center.x, y:center.y - heightToCenter*2))
        context.addLine(to: CGPoint(x:center.x + triangleWidth/2, y:center.y + heightToCenter))
        context.addLine(to: CGPoint(x:center.x - triangleWidth/2, y:center.y + heightToCenter))
        context.closePath()
        context.fillPath()

Upvotes: 1

SwiftArchitect
SwiftArchitect

Reputation: 48524

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()
}

Upvotes: 5

omz
omz

Reputation: 53561

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.

Upvotes: 23

Related Questions