如何以编程方式绘制三angular形

我有一个三angular形求解器,我想要一个方法来使用我从答案中得到的值在与之匹配的屏幕上绘制一个三angular形。

如果你inheritance一个UIView,你可以在drawRect中实现这样的一个绘制三angular形:

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

Swift 3相当于progrmr的回答:

 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() } 
 - (void)drawRect:(CGRect)rect { CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextClearRect(ctx, rect); // Draw a triangle CGContextSetRGBFillColor(ctx, 255, 160, 122, 1); CGContextBeginPath(ctx); CGContextMoveToPoint (ctx, 290, 35); // top CGContextAddLineToPoint(ctx, 350, 165); // right CGContextAddLineToPoint(ctx, 230,165); // left CGContextClosePath(ctx); CGContextSetRGBFillColor(ctx, 1, 1, 1, 1); CGContextFillPath(ctx); }