iPhone矢印キャンバス

指でなぞって矢印の方向を変えるお絵書きキャンバスiPhoneアプリのサンプルコードを描いてみます。

#import “ViewController.h”

@interface ViewController ()

@property (nonatomic, weak) UIView *select;

@property (nonatomic) CGPoint selectPoint;

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor colorWithRed:0 green:0.4 blue:0 alpha:1];

    [self createArrows];

}

– (void)createArrows

{

    for (int i=0; i< 16 * 25; i++) {

        float x = (i % 16) * 20 + 10;

        float y = (i / 16) * 20 + 30;

        UIView *arrow = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];

        arrow.tag = 1;

        arrow.center = CGPointMake(x, y);

        arrow.backgroundColor = [UIColor clearColor];

        [self.view addSubview:arrow];

        

        UIBezierPath *path = [UIBezierPath bezierPath];

        [path moveToPoint:CGPointMake(4, 4)];

        [path addLineToPoint:CGPointMake(16, 10)];

        [path addLineToPoint:CGPointMake(4, 16)];

        CAShapeLayer *al = [CAShapeLayer layer];

        al.path = path.CGPath;

        al.fillColor = [UIColor clearColor].CGColor;

        al.strokeColor = [UIColor whiteColor].CGColor;

        al.lineWidth = 2;

        [arrow.layer addSublayer:al];

    }

}

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

{

    CGPoint p = [[touches anyObject] locationInView:self.view];

    UIView *v = [self.view hitTest:p withEvent:nil];

    if (v.tag != 1) {

        return;

    }

    

    if (self.select != v) {

        if (self.select) {

            float dx = self.selectPoint.x – p.x;

            float dy = self.selectPoint.y – p.y;

            float angle = atan2f(dx, -dy) + M_PI * 0.5;

            self.select.transform = CGAffineTransformMakeRotation(angle);

        }

        self.select = v;

        self.selectPoint = p;

    }

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end