UIPanGestureRecognizerを使って、指のX方向、Y方向の早さをメータで表示するようなiPhoneアプリを描いてみます。
動作イメージ
XcodeからiOS6 iPhone Simulatorで動かすとこんな感じになります。
サンプルコード
#import “ViewController.h”
#import <QuartzCore/QuartzCore.h>
@interface ViewController () {
UIView *handA;
UIView *handB;
}
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor blackColor];
[self createSpeedMeterA];
[self createSpeedMeterB];
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];
[self.view addGestureRecognizer:pan];
}
– (void)createSpeedMeterA
{
UIView *speedMeter = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 120, 80)];
[self.view addSubview:speedMeter];
UIBezierPath *path = [UIBezierPath bezierPath];
[path addArcWithCenter:CGPointMake(60, 100) radius:50 startAngle:M_PI*1.2 endAngle:M_PI*1.8 clockwise:YES];
CAShapeLayer *sl = [CAShapeLayer layer];
sl.strokeColor = [UIColor lightGrayColor].CGColor;
sl.fillColor = [UIColor clearColor].CGColor;
sl.lineWidth = 30;
sl.path = path.CGPath;
[speedMeter.layer addSublayer:sl];
handA = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 3, 40)];
handA.layer.anchorPoint = CGPointMake(0.5, 1.0);
handA.layer.position = CGPointMake(60, 85);
handA.backgroundColor = [UIColor redColor];
handA.transform = CGAffineTransformMakeRotation(-M_PI/3.0);
[speedMeter addSubview:handA];
}
– (void)createSpeedMeterB
{
UIView *speedMeter = [[UIView alloc] initWithFrame:CGRectMake(180, 20, 120, 80)];
[self.view addSubview:speedMeter];
UIBezierPath *path = [UIBezierPath bezierPath];
[path addArcWithCenter:CGPointMake(60, 100) radius:50 startAngle:M_PI*1.2 endAngle:M_PI*1.8 clockwise:YES];
CAShapeLayer *sl = [CAShapeLayer layer];
sl.strokeColor = [UIColor lightGrayColor].CGColor;
sl.fillColor = [UIColor clearColor].CGColor;
sl.lineWidth = 30;
sl.path = path.CGPath;
[speedMeter.layer addSublayer:sl];
handB = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 3, 40)];
handB.layer.anchorPoint = CGPointMake(0.5, 1.0);
handB.layer.position = CGPointMake(60, 85);
handB.backgroundColor = [UIColor redColor];
handB.transform = CGAffineTransformMakeRotation(-M_PI/3.0);
[speedMeter addSubview:handB];
}
– (void)move:(UIPanGestureRecognizer *)gr
{
CGPoint velocity = [gr velocityInView:self.view];
float speedX = MIN(abs(velocity.x) / 100.0, 2 * M_PI/3.0) – M_PI/3.0;
handA.transform = CGAffineTransformMakeRotation(speedX);
float speedY = MIN(abs(velocity.y) / 100.0, 2 * M_PI/3.0) – M_PI/3.0;
handB.transform = CGAffineTransformMakeRotation(speedY);
if (gr.state == UIGestureRecognizerStateEnded) {
handA.transform = CGAffineTransformMakeRotation(-M_PI/3.0);
handB.transform = CGAffineTransformMakeRotation(-M_PI/3.0);
}
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end