Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a triangle programmatically

I have a triangle solver, I want a way to use the values I get from the answer to draw a triangle to the screen that matches it.

like image 700
user804306 Avatar asked Jul 14 '11 17:07

user804306


People also ask

How do you make a triangle in Javascript?

js | triangle() Function. The triangle() function is an inbuilt function in p5. js which is used to draw a triangle in a plane. This function accepts three vertices of triangle.


2 Answers

If you subclass a UIView you can implement something like this in drawRect to draw a triangle:

-(void)drawRect:(CGRect)rect {     CGContextRef ctx = UIGraphicsGetCurrentContext();      CGContextBeginPath(ctx);     CGContextMoveToPoint   (ctx, CGRectGetMinX(rect), CGRectGetMinY(rect));  // top left     CGContextAddLineToPoint(ctx, CGRectGetMaxX(rect), CGRectGetMidY(rect));  // mid right     CGContextAddLineToPoint(ctx, CGRectGetMinX(rect), CGRectGetMaxY(rect));  // bottom left     CGContextClosePath(ctx);      CGContextSetRGBFillColor(ctx, 1, 1, 0, 1);     CGContextFillPath(ctx); } 
like image 103
progrmr Avatar answered Sep 19 '22 01:09

progrmr


Swift 3 equivalent for progrmr's answer:

override func draw(_ rect: CGRect) {      guard let context = UIGraphicsGetCurrentContext() else { return }      context.beginPath()     context.move(to: CGPoint(x: rect.minX, y: rect.minY))     context.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))     context.addLine(to: CGPoint(x: (rect.minX), y: rect.maxY))     context.closePath()      context.setFillColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)     context.fillPath() } 
like image 35
Santosh Avatar answered Sep 22 '22 01:09

Santosh