How to draw a triangle programmatically

旧时模样 提交于 2019-12-13 04:29:23

问题


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.


回答1:


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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/16073246/drawing-a-triangle-in-uiview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!