将曲线添加到我的矩形

Cor*_*ory 3 objective-c uiview drawrect

我想在Objective-c中绘制一个阴阳,但我无法弄清楚如何去做.我创建了两个连接的矩形.我无法弄清楚如何制作矩形曲线的线条,以便我可以用它们制作一个圆圈.到目前为止,这是我的代码.

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextAddRect(context, CGRectMake(60, 150, 80, 10));
CGContextStrokePath(context);

CGContextAddRect(context, CGRectMake(60, 150, 190, 10));
CGContextStrokePath(context);
Run Code Online (Sandbox Code Playgroud)

是否有更简单的方法来创建目标-c中的阴阳,或者我是朝着正确的方向?我是Objective-c和编程的新手.

Rob*_*Rob 6

我建议用弧线(实际上是一系列半圆)代替圆角矩形.例如,将一部分视为三个独立的半圆:

阴阳招

然后您可以像这样绘制这些弧:

CGContextAddArc(context, center.x, center.y - side / 4.0, side / 4.0, M_PI_2, -M_PI_2, TRUE); // red part
CGContextAddArc(context, center.x, center.y + side / 4.0, side / 4.0, M_PI_2, -M_PI_2, NO);   // blue part
CGContextAddArc(context, center.x, center.y,              side / 2.0, -M_PI_2, M_PI_2, YES);  // dark grey stroke
Run Code Online (Sandbox Code Playgroud)

但显然,你可能实际上不会绘制这些笔划,而只是填充它们,然后对符号的底部重复此过程:

- (void)drawRect:(CGRect)rect {
    CGFloat side = MIN(rect.size.width, rect.size.height);                       // length of the side of the square in which the symbol will rest
    CGPoint center = CGPointMake(rect.size.width / 2.0, rect.size.height / 2.0); // the center of that square

    CGContextRef context = UIGraphicsGetCurrentContext();

    // draw white part

    CGContextAddArc(context, center.x, center.y - side / 4.0, side / 4.0, M_PI_2, -M_PI_2, TRUE);
    CGContextAddArc(context, center.x, center.y + side / 4.0, side / 4.0, M_PI_2, -M_PI_2, NO);
    CGContextAddArc(context, center.x, center.y,              side / 2.0, -M_PI_2, M_PI_2, YES);
    CGContextClosePath(context);

    CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextFillPath(context);

    // draw black part

    CGContextAddArc(context, center.x, center.y - side / 4.0, side / 4.0, M_PI_2, -M_PI_2, TRUE);
    CGContextAddArc(context, center.x, center.y + side / 4.0, side / 4.0, M_PI_2, -M_PI_2, NO);
    CGContextAddArc(context, center.x, center.y,              side / 2.0, -M_PI_2, M_PI_2, NO);
    CGContextClosePath(context);

    CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
    CGContextFillPath(context);

    // draw black dot

    CGContextAddArc(context, center.x, center.y - side / 4.0, side / 12.0, 0, M_PI * 2.0, YES);
    CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
    CGContextFillPath(context);

    // draw white dot

    CGContextAddArc(context, center.x, center.y + side / 4.0, side / 12.0, 0, M_PI * 2.0, YES);
    CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextFillPath(context);
}
Run Code Online (Sandbox Code Playgroud)

产量:

阴阳