Draw a Curvilinear Rectangle inside a circle on iOS

自闭症网瘾萝莉.ら 提交于 2019-12-13 08:30:44

问题


I'm trying to draw a diversity wheel (a circle with curvilinear rectangles inside) see:

circle http://api.ning.com/files/oKZwndeqeam7%2aMiO7f4BDUT%2aAgw3WsK3kW-b-wXjR8gCrCqVAv3RpyBAdi%2adYSLaca0kAYCY0Wk13bSHDnEbOVR1NNUuYotV/diversity_wheel3.JPG?width=500

I know how to draw a circle, but I don't know how to draw the curvilinear rectangle based on the circle coordinates.

How can I do this?


回答1:


Since you know how to draw circles, just add some lines to its center and you get something like the image you posted:

- (void)drawRect:(CGRect)rect
{
    CGPoint centerPoint = self.center;
    CGFloat circleWidth = 30;
    int numCircles = 4;

    [[UIColor colorWithHue:0.53 saturation:1 brightness:0.6 alpha:1] setStroke];

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    for(int i=numCircles-1;i>=0;i--){
        //calculate some color
        CGFloat colorModifier = ((numCircles-i)/(float)numCircles);
        [[UIColor colorWithHue:0.53 saturation:colorModifier*0.8+0.2 brightness:1-colorModifier*0.4 alpha:1] setFill];

        CGFloat radius = circleWidth*(i+1);

        //draw the circle
        CGContextFillEllipseInRect(ctx, CGRectMake(centerPoint.x-radius, centerPoint.y-radius, 2*radius, 2*radius));
        CGContextStrokeEllipseInRect(ctx, CGRectMake(centerPoint.x-radius, centerPoint.y-radius, 2*radius, 2*radius));

        if(i>0){
            //just add a random number of dividers here
            int numDivider = 3+(arc4random()%5);
            float angleStep = 2*M_PI/numDivider;
            for(int j=0;j<numDivider;j++){
                CGFloat x = centerPoint.x + sinf(j*angleStep)*radius;
                CGFloat y = centerPoint.y + cosf(j*angleStep)*radius;
                CGContextMoveToPoint(ctx, centerPoint.x, centerPoint.y);
                CGContextAddLineToPoint(ctx, x, y);
                CGContextStrokePath(ctx);
            }
        }
    }
}

A possibility to just draw a single curved rectangle would be to draw an arc and erase an inner circle. Like this:

    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:self.center];
    [path addArcWithCenter:self.center radius:150 startAngle:-0.3 endAngle:0.3 clockwise:YES];
    [path fill];

    UIBezierPath *innerPath = [UIBezierPath bezierPath];
    [innerPath moveToPoint:self.center];
    [innerPath addArcWithCenter:self.center radius:120 startAngle:0 endAngle:2*M_PI clockwise:YES];
    CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeClear);
    [innerPath fill];


来源:https://stackoverflow.com/questions/24579771/draw-a-curvilinear-rectangle-inside-a-circle-on-ios

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