赤と緑のまるをすきなところに動かして、
ひもをくねくねさせてあそぼう!
という感じで子供向けiPhoneアプリのサンプルコードを書きました。
ポイント
UIBezierPathのaddQuadCurveToPointを利用しています。
pointとcontrolPointに対応するViewを表示しておいて、
PanGestureでポイントを移動できるようにすることで、
くねくね曲げています。
環境
今回つくったiPhoneアプリサンプルは、
XcodeのiOS6 iPhone Simulatorで動かしています。
サンプルコード
#import “ViewController.h”
#import <QuartzCore/QuartzCore.h>
@interface ViewController () {
CGPoint p1, p2, p3, p4, p5;
CGPoint cp2, cp3, cp4, cp5;
CAShapeLayer *sl;
}
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor blackColor];
sl = [[CAShapeLayer alloc] initWithLayer:self.view.layer];
sl.fillColor = [UIColor clearColor].CGColor;
sl.strokeColor = [UIColor greenColor].CGColor;
sl.lineWidth = 5;
[self.view.layer addSublayer:sl];
p1 = CGPointMake(160, 40);
p2 = CGPointMake(160, 140);
p3 = CGPointMake(160, 240);
p4 = CGPointMake(160, 340);
p5 = CGPointMake(160, 440);
cp2 = CGPointMake(160, 140);
cp3 = CGPointMake(160, 240);
cp4 = CGPointMake(160, 340);
cp5 = CGPointMake(160, 440);
[self updateLine];
CGPoint points[5] = {p1, p2, p3, p4, p5};
for (int i=0; i<5; i++) {
UIView *pv = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
pv.tag = i;
pv.layer.cornerRadius = 15;
pv.backgroundColor = [UIColor greenColor];
pv.center = points[i];
[self.view addSubview:pv];
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panP:)];
[pv addGestureRecognizer:pan];
}
CGPoint cpoints[4] = {cp2, cp3, cp4, cp5};
for (int i=0; i<4; i++) {
UIView *cpv = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 14, 14)];
cpv.tag = i;
cpv.layer.cornerRadius = 7;
cpv.backgroundColor = [UIColor redColor];
cpv.center = cpoints[i];
[self.view addSubview:cpv];
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panCP:)];
[cpv addGestureRecognizer:pan];
}
}
– (void)panP:(UIPanGestureRecognizer*)gr
{
CGPoint p = [gr locationInView:self.view];
gr.view.center = p;
switch (gr.view.tag) {
case 0: p1 = p; break;
case 1: p2 = p; break;
case 2: p3 = p; break;
case 3: p4 = p; break;
case 4: p5 = p; break;
}
[self updateLine];
}
– (void)panCP:(UIPanGestureRecognizer*)gr
{
CGPoint p = [gr locationInView:self.view];
gr.view.center = p;
switch (gr.view.tag) {
case 0: cp2 = p; break;
case 1: cp3 = p; break;
case 2: cp4 = p; break;
case 3: cp5 = p; break;
}
[self updateLine];
}
– (void)updateLine
{
UIBezierPath *path = [[UIBezierPath alloc] init];
[path moveToPoint:p1];
[path addQuadCurveToPoint:p2 controlPoint:cp2];
[path addQuadCurveToPoint:p3 controlPoint:cp3];
[path addQuadCurveToPoint:p4 controlPoint:cp4];
[path addQuadCurveToPoint:p5 controlPoint:cp5];
sl.path = path.CGPath;
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end