Objective-C (iOS): 画面のタッチと描画

TouchViewController

Objective-C: TouchViewController.h

#import <UIKit/UIKit.h>
#import "TouchView.h"

@interface TouchViewController : UIViewController

@end

Objective-C: TouchViewController.m

#import "TouchViewController.h"

@interface TouchViewController ()

@end

@implementation TouchViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    TouchView *touchView = [[TouchView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:touchView];
}

@end

Objective-C: TouchView.h

#import <UIKit/UIKit.h>

@interface TouchView : UIView

@property (strong, nonatomic) NSMutableArray *touchList;

@end

Objective-C: TouchView.m

#import "TouchView.h"

@implementation TouchView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.multipleTouchEnabled = YES;
        self.touchList = [NSMutableArray array];
        
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    [[UIColor redColor] set];
    
    const int RADIUS = 100;
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f};
    for (int i = self.touchList.count-1; i >= 0; i--) {
        
        CGPoint point = [[self.touchList objectAtIndex:i] locationInView:self];
        CGContextSetFillColor(context, red);
        CGContextFillEllipseInRect(context, CGRectMake(point.x - RADIUS*.5, point.y - RADIUS*.5, RADIUS, RADIUS));
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSArray *touchObjects = [touches allObjects];
    for (int i = touchObjects.count-1; i >= 0; i--) {
        [self.touchList addObject:[touchObjects objectAtIndex:i]];
    }
    [self setNeedsDisplay];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self setNeedsDisplay];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSArray *touchObjects = [touches allObjects];
    for (int i = touchObjects.count-1; i >= 0; i--) {
        NSObject *touch = [touchObjects objectAtIndex:i];
        if ([self.touchList containsObject:touch]) {
            [self.touchList removeObject:touch];
        }
    }
    [self setNeedsDisplay];
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.touchList removeAllObjects];
    [self setNeedsDisplay];
}

@end