コッホ曲線(KochCurve)を書いてみます。
(XcodeのiOS6 iPhone Simulatorで動かしています。)
概要
フラクタル図形を書いてみようと思い、
シンプルそうだったのでコッホ曲線をチョイス。
タッチで、正三角形の作図を一つ増加させていきます。
ポイント
直線を3等分して、正三角形にしていきます。
三角形の頂点は60度のsin, cosを利用して算出
こんな感じ。
CGPoint b = CGPointMake(
c60 * (a.x – c.x) – s60 * (a.y – c.y) + c.x,
s60 * (a.x – c.x) + c60 * (a.y – c.y) + c.y
);
サンプルコード
#import “ViewController.h”
@interface KochCurve : UIView {
NSMutableArray *points;
}
– (id)initWithLineStart:(CGPoint)start end:(CGPoint)end;
– (void)nUP;
@end
@implementation KochCurve
– (id)initWithLineStart:(CGPoint)start end:(CGPoint)end
{
self = [self initWithFrame:CGRectMake(0, 0, 320, 480)];
if (self) {
points = [[NSMutableArray alloc] init];
[points addObject:[NSValue valueWithCGPoint:start]];
[points addObject:[NSValue valueWithCGPoint:end]];
}
return self;
}
– (void)drawRect:(CGRect)rect
{
[[UIColor whiteColor] setStroke];
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextClearRect(ctx, self.bounds);
CGPoint start = [[points objectAtIndex:0] CGPointValue];
CGContextMoveToPoint(ctx, start.x, start.y);
for (int i=1; i<[points count]; i++) {
CGPoint p = [[points objectAtIndex:i] CGPointValue];
CGContextAddLineToPoint(ctx, p.x, p.y);
}
CGContextStrokePath(ctx);
}
– (void)nUP
{
NSMutableArray *newArr = [points mutableCopy];
for (int i = 0; i < [points count] – 1; i++) {
CGPoint p0 = [[points objectAtIndex:i] CGPointValue];
CGPoint p1 = [[points objectAtIndex:i + 1] CGPointValue];
CGPoint a = CGPointMake((p1.x – p0.x) * (1.0/3.0) + p0.x, (p1.y – p0.y) * (1.0/3.0) + p0.y);
CGPoint c = CGPointMake((p1.x – p0.x) * (2.0/3.0) + p0.x, (p1.y – p0.y) * (2.0/3.0) + p0.y);
double s60 = sin(60 * M_PI / 180.0);
double c60 = cos(60 * M_PI / 180.0);
CGPoint b = CGPointMake(
c60 * (a.x – c.x) – s60 * (a.y – c.y) + c.x,
s60 * (a.x – c.x) + c60 * (a.y – c.y) + c.y
);
int index = [newArr indexOfObject:[points objectAtIndex:i]];
[newArr insertObject:[NSValue valueWithCGPoint:a] atIndex:index + 1];
[newArr insertObject:[NSValue valueWithCGPoint:b] atIndex:index + 2];
[newArr insertObject:[NSValue valueWithCGPoint:c] atIndex:index + 3];
}
points = newArr;
[self setNeedsDisplay];
}
@end
@interface ViewController () {
KochCurve *kc;
}
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
kc = [[KochCurve alloc] initWithLineStart:CGPointMake(10, 10) end:CGPointMake(10, 460)];
[self.view addSubview:kc];
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[kc nUP];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end