タッチ位置に矩形を表示するサンプル(iOS)

Coronaで作成したタッチ位置に矩形を表示するサンプルをiOSでも書いてみました。

f:id:noriok:20120404003030p:plain

// ViewController.h
#import <UIKit/UIKit.h>
#import "MyView.h"

@interface ViewController : UIViewController {
    MyView* _myView;
}

@end
// ViewController.m
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    MyView* myView = [[MyView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    myView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:myView];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

@end
// MyView.h
#import <UIKit/UIKit.h>

@interface MyView : UIView {
    CGPoint _point;
    int _angle;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;

- (void)task:(NSTimer*)timer;

@end
// MyView.m
#import "MyView.h"

@implementation MyView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        _point = CGPointMake(0, 0);
        _angle = 0;
        
        [NSTimer scheduledTimerWithTimeInterval:0.03f target:self selector:@selector(task:) userInfo:nil repeats:YES];
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(c, [UIColor blueColor].CGColor);
    CGContextTranslateCTM(c, _point.x, _point.y);
    CGContextRotateCTM(c, _angle*M_PI/180.0);
    CGContextTranslateCTM(c, -_point.x, -_point.y);

    const int size = 50;
    CGRect r = CGRectMake(_point.x - (size/2.0), _point.y - (size/2.0), size, size);    
    CGContextFillRect(c, r);
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
    UITouch* touch = [touches anyObject];
    _point = [touch locationInView:self];
    [self setNeedsDisplay];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch* touch = [touches anyObject];
    _point = [touch locationInView:self];
    [self setNeedsDisplay];
}

- (void)task:(NSTimer*)timer {
    _angle += 10;
    if (_angle >= 360) _angle -= 360;
    [self setNeedsDisplay];
}

@end


次は、タッチ位置の周りを回るように矩形を描画してみよう。