ios 如何以编程方式绘制三角形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6697614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:45:57 来源:igfitidea点击:
How to draw a triangle programmatically
提问by user804306
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.
我有一个三角形求解器,我想要一种方法来使用我从答案中获得的值在与其匹配的屏幕上绘制一个三角形。
回答by progrmr
If you subclass a UIView you can implement something like this in drawRect to draw a triangle:
如果你继承 UIView 你可以在 drawRect 中实现类似的东西来绘制一个三角形:
-(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);
}
回答by Santosh
Swift 3equivalent for progrmr
's answer:
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()
}
回答by Anna Korr
- (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);
}