顕微鏡とか、望遠鏡でなにかを覗いているような気分を味わう

(XcodeのiOS6 iPhone Simulatorで試しています。)

ポイント

肉眼では見えない程度の大きさの文字を表示、

指でなぞったところを読めるような大きさに拡大して

別のViewに映す。

サンプルコード

#import “ViewController.h”

#import <QuartzCore/QuartzCore.h>

@interface ViewController () {

    UIView *lens;

    UIView *plate;

}

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    

    self.view.backgroundColor = [UIColor blackColor];

    lens = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];

    lens.center = CGPointMake(150, 100);

    lens.backgroundColor = [UIColor whiteColor];

    lens.layer.cornerRadius = 50;

    lens.layer.masksToBounds = YES;

    [self.view addSubview:lens];

    

    plate = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 400, 400)];

    plate.backgroundColor = [UIColor whiteColor];

    plate.transform = CGAffineTransformMakeScale(0.3, 0.3);

    plate.center = CGPointMake(150,250);

    [self.view addSubview:plate];

    for (int i=0; i<100; i++) {

        int x = (i/10) * 30 + 40;

        int y = (i%10) * 30 + 40;

        

        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, y, 40, 20)];

        label.textAlignment = 1;

        label.textColor = [UIColor colorWithHue:i *0.005 saturation:0.8 brightness:0.7 alpha:1.0];

        label.text = [NSString stringWithFormat:@”%d”, i];

        [plate addSubview:label];

    }

}

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

{

    CGPoint p = [[touches anyObject] locationInView:plate];

    [self zoomPoint:p];

}

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

{

    CGPoint p = [[touches anyObject] locationInView:plate];

    [self zoomPoint:p];

}

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

{

    for (UIView *v in lens.subviews) {

        [v removeFromSuperview];

    }

}

– (void)zoomPoint:(CGPoint)p

{

    for (UIView *v in lens.subviews) {

        [v removeFromSuperview];

    }

    

    for (UILabel *l in plate.subviews) {

        CGRect rect = CGRectMake(p.x100, p.y100, 200, 200);

        if (CGRectIntersectsRect(l.frame, rect)) {

            UILabel *cp = [[UILabel alloc] initWithFrame:l.frame];

            cp.center = CGPointMake(cp.center.x – p.x + 30, cp.center.y – p.y + 30);

            cp.text = l.text;

            cp.textColor = l.textColor;

            cp.backgroundColor = [UIColor clearColor];

            [lens addSubview:cp];

        }

    }

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end