iPhoneテキスト回り込み

ABCの文字がカボチャのジャックの周りを囲むような、iPhoneアプリを描いてみる。

動作イメージ
XcodeからiOS7 iPhone Simulatorで動かすとこんな感じになります。

サンプルコード

#import “ViewController.h”

@interface ViewController ()

@property (strong, nonatomic) UITextView *tv;

@property (strong, nonatomic) UIImageView *pumpkin;

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    

    self.view.backgroundColor = [UIColor blackColor];

    

    self.tv = [[UITextView alloc] initWithFrame:CGRectMake(10, 100, 300, 300)];

    [self.view addSubview:self.tv];

    self.tv.backgroundColor = [UIColor clearColor];

    self.tv.text = @”ABCDEFGHIJKLMNOPQRSTUVWXYZ”;

    self.tv.textColor = [UIColor colorWithRed:0.4 green:0 blue:0 alpha:1];

    self.tv.font = [UIFont systemFontOfSize:60];

    

    self.tv.textContainer.exclusionPaths = @[[UIBezierPath bezierPathWithOvalInRect:CGRectMake(50, 0, 30, 30)]];

    self.tv.userInteractionEnabled = NO;

    

    self.pumpkin.frame = CGRectMake(60, 100, 50, 50);

}

– (UIImageView *)pumpkin

{

    if (!_pumpkin) {

        UIImage *img = [UIImage imageNamed:@”pumpkin”];

        _pumpkin = [[UIImageView alloc] initWithImage:img];

        [self.view addSubview:_pumpkin];

        

        _pumpkin.userInteractionEnabled = YES;

        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];

        [_pumpkin addGestureRecognizer:pan];

    }

    return _pumpkin;

}

– (void)move:(UIPanGestureRecognizer*)gr

{

    CGPoint p1 = [gr locationInView:self.view];

    CGPoint p2 = [gr locationInView:self.tv];

    

    gr.view.center = p1;

    self.tv.textContainer.exclusionPaths = @[[UIBezierPath bezierPathWithOvalInRect:CGRectMake(p2.x, p2.y, 30, 30)]];

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end