iPhone完全グラフ

完全グラフの点を増やしていくとどうなるのか試してみるiPhoneアプリのサンプルコードを描いてみます。



#import “ViewController.h”

@interface ViewController ()

@property (nonatomic, weak) CAShapeLayer *sl;

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor colorWithWhite:0.98 alpha:1];

    [self createStepper];

}

– (void)createStepper

{

    UIStepper *stepper = [[UIStepper alloc] init];

    stepper.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMaxY(self.view.frame) – 100);

    stepper.minimumValue = 2;

    stepper.maximumValue = 30;

    [self.view addSubview:stepper];

    [stepper addTarget:self action:@selector(step:) forControlEvents:UIControlEventValueChanged];

}

– (void)step:(UIStepper *)sender

{

    sender.userInteractionEnabled = NO;

    [self clearDisplay];

    

    CGPoint o = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMidY(self.view.frame) + 30);

    float r = 130;

    float dAngle = 2.0 * M_PI / sender.value;

    UIBezierPath *path = [UIBezierPath bezierPath];

    for (int i=0; i<sender.value; i++) {

        float x = r * cos(i * dAngle) + o.x;

        float y = r * sin(i * dAngle) + o.x;

        UIView *dot = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];

        dot.tag = 1;

        dot.backgroundColor = [UIColor blackColor];

        dot.layer.cornerRadius = 5.0;

        dot.layer.borderColor = [UIColor lightGrayColor].CGColor;

        dot.layer.borderWidth = 2;

        dot.center = CGPointMake(x, y);

        [self.view addSubview:dot];

        

        NSPredicate *pred = [NSPredicate predicateWithFormat:@”tag == %d”, 1];

        for (UIView *v in [self.view.subviews  filteredArrayUsingPredicate:pred]) {

            [path moveToPoint:dot.center];

            [path addLineToPoint:v.center];

        }

    }

    self.sl = [CAShapeLayer layer];

    self.sl.path = path.CGPath;

    self.sl.strokeColor = [UIColor lightGrayColor].CGColor;

    self.sl.lineWidth = 2;

    [self.view.layer addSublayer:self.sl];

    

    CABasicAnimation *stroke = [CABasicAnimation animationWithKeyPath:@”strokeEnd”];

    stroke.fromValue = @(0);

    stroke.toValue = @(1);

    stroke.duration = 3.0;

    [self.sl addAnimation:stroke forKey:nil];

    

    sender.userInteractionEnabled = YES;

}

– (void)clearDisplay

{

    [self.view.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

        if (![obj isKindOfClass:[UIStepper class]]) {

            [obj removeFromSuperview];

        }

    }];

    [self.sl removeFromSuperlayer];

}

@end