How to draw a triangle using Core Graphics - Mac?

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

example triangle

How to do it with Cocoa? In drawRect: :? I do not know how to draw.

+4
source share
3 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]; } 

That should get you started; it draws a red triangle on a 100x100-sized view. You usually calculate coordinates dynamically based on the size of the view, instead of using hardcoded values, of course.

+21
source

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() } 
+4
source

iOS + Swift5 (context handling updated, width difference added)

  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() 
0
source

All Articles