花びらを一枚、二枚と千切って、好き嫌い
子供の頃に、一度はやったことがある花占いを
アプリのサンプルで作ってみました。

ポイント
花びらは、BezierPathで描いてます。
横長長方形のUIViewをforループの中で、
rotation、横方向へのtranslateと変形させると
簡単に円上に花びらを配置できます。


サンプルコード


#import “ViewController.h”

#import <QuartzCore/QuartzCore.h>

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor blueColor];

    

    [self createFlower];

}

– (void)createFlower

{

    UIView *flower = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 300)];

    flower.backgroundColor = [UIColor clearColor];

    [self.view addSubview:flower];

    

    UIView *stem = [[UIView alloc] initWithFrame:CGRectMake(95, 100, 20, 250)];

    stem.backgroundColor = [UIColor greenColor];

    [flower addSubview:stem];

    

    

    UIView *circle = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 70, 70)];

    circle.layer.cornerRadius = 30;

    circle.backgroundColor = [UIColor yellowColor];

    circle.center = CGPointMake(100, 100);

    [flower addSubview:circle];

    

    UIBezierPath *path = [[UIBezierPath alloc] init];

    [path moveToPoint:CGPointMake(0, 10)];

    [path addQuadCurveToPoint:CGPointMake(0, 20) controlPoint:CGPointMake(5, 15)];

    [path addCurveToPoint:CGPointMake(0, 10) controlPoint1:CGPointMake(120, 60) controlPoint2:CGPointMake(120, –30)];

    

    int numberOfPetals = arc4random() % 5 + 15;

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

        UIView *petal = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];

        petal.center = CGPointMake(100, 100);

        petal.backgroundColor = [UIColor clearColor];

        

        CAShapeLayer *sl = [[CAShapeLayer alloc] initWithLayer:petal.layer];

        sl.fillColor = [UIColor whiteColor].CGColor;

        sl.strokeColor = [UIColor blackColor].CGColor;

        sl.lineWidth = 0.2;

        sl.path = path.CGPath;

        

        [petal.layer addSublayer:sl];

        

        float angle = i * 2 * M_PI / (float)numberOfPetals;

        CGAffineTransform trans = CGAffineTransformMakeRotation(angle);

        trans = CGAffineTransformTranslate(trans, 70, 0);

        petal.transform = trans;

        [flower addSubview:petal];

        

        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];

        [petal addGestureRecognizer:tap];

    }

    

    flower.center = CGPointMake(160, 250);

}

– (void)tap:(UITapGestureRecognizer*)gr

{

    [UIView animateWithDuration:0.2 animations:^{

        gr.view.transform = CGAffineTransformTranslate(gr.view.transform, 50, 0);

    } completion:^(BOOL finished) {

        [UIView animateWithDuration:2.0 animations:^{

            gr.view.center = CGPointMake(gr.view.center.x, 600);

        }];

    }];

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end