アルキメデスの螺旋(Archimedean spiral)をUIViewで書いてみる。

(XcodeのiOS6 Simulatorを使って試しています。)

ポイント

・ r = a + bθを利用してdrawRectで描画

・タッチしているあいだは、transformで回転させる

サンプルコード

//——————

// Spiral.m

//——————

#import “Spiral.h”

@implementation Spiral

– (void)drawRect:(CGRect)rect

{

    CGPoint o = CGPointMake(self.bounds.size.width * 0.5, self.bounds.size.height * 0.5);

    

    [[UIColor whiteColor] setStroke];

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetLineWidth(context, 4.0);

    CGContextMoveToPoint(context, o.x, o.y);

    for (int i=0; i<1000; i++) {

        CGPoint p = [self calculatePointWithNumber:i];

        CGContextAddLineToPoint(context, p.x + o.x, p.y + o.y);

    }

    CGContextStrokePath(context);

}

– (CGPoint)calculatePointWithNumber:(int)num

{

    float a = 5.0;

    float b = 5.0;

    float th = (2 * M_PI / 100) * num;

    float r = a + b * th;

    return CGPointMake(r * sin(th), r * cos(th));

}

@end

//——————

// ViewController.m

//——————

#import “ViewController.h”

#import “Spiral.h”

#import <QuartzCore/QuartzCore.h>

@interface ViewController () {

    CADisplayLink *timer;

    UIView *spiralView;

    BOOL spin;

}

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

}

– (void)viewDidAppear:(BOOL)animated

{

    [super viewDidAppear:animated];

    

    // create spiral View

    spiralView = [[Spiral alloc] initWithFrame:CGRectMake(0,0,600,600)];

    spiralView.backgroundColor = [UIColor clearColor];

    self.view.center = CGPointMake(160, 240);

    spiralView.center = self.view.center;

    spiralView.backgroundColor = [UIColor purpleColor];

    [self.view addSubview:spiralView];

    

    [self start];

}

– (void)start

{

    timer = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateDisp:)];

    [timer addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];

}

– (void)updateDisp:(CADisplayLink*)sender

{

    if (spin) {

        CATransform3D transform = spiralView.layer.transform;

        spiralView.layer.transform = CATransform3DRotate(transform, M_PI * 0.02, 0,0, 1.0);

    }

}

– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    // 画面をタッチしているあいだは回転

    spin = YES;

}

– (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

{

    // 指を離したら回転を止める

    spin = NO;

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end