iPhone 玉グラフ

玉の中をグラフのように色付けするiPhoneアプリのサンプルコードを描いてみます。


#import “ViewController.h”

@import SceneKit;

@interface ViewController ()

@property (nonatomic, weak) SCNView *sceneView;

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    [self setupScene];

    [self createSphere];

    [self createCamera];

}

– (void)setupScene {

    SCNView *sv = [[SCNView alloc] initWithFrame:self.view.bounds];

    sv.scene = [SCNScene scene];

    sv.autoenablesDefaultLighting = YES;

    sv.allowsCameraControl = YES;

    [self.view addSubview:sv];

    self.sceneView = sv;

}

– (void)createSphere {

    

    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointZero radius:5 startAngle:0 endAngle:M_PI clockwise:NO];

    path.flatness = 0.1;

    SCNShape *shape = [SCNShape shapeWithPath:path extrusionDepth:0.4];

    shape.firstMaterial.diffuse.contents = [UIColor darkGrayColor];

    

    UIBezierPath *path2 = [UIBezierPath bezierPathWithArcCenter:CGPointZero radius:4 startAngle:0 endAngle:M_PI clockwise:NO];

    path2.flatness = 0.02;

    SCNShape *shapeRed = [SCNShape shapeWithPath:path2 extrusionDepth:0.41];

    shapeRed.firstMaterial.diffuse.contents = [UIColor redColor];

    

    

    UIBezierPath *path3 = [UIBezierPath bezierPathWithArcCenter:CGPointZero radius:2.5 startAngle:0 endAngle:M_PI clockwise:NO];

    path3.flatness = 0.02;

    SCNShape *shapeGreen = [SCNShape shapeWithPath:path3 extrusionDepth:0.42];

    shapeGreen.firstMaterial.diffuse.contents = [UIColor greenColor];

    

    float dw = M_PI / 50.0;

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

        SCNNode *arcNode = [SCNNode nodeWithGeometry:shape];

        arcNode.transform = SCNMatrix4Rotate(arcNode.transform, i * dw, 1, 0, 0);

        arcNode.name = [NSString stringWithFormat:@”no%d”, i];

        [self.sceneView.scene.rootNode addChildNode:arcNode];

        

        if (i==74 || i==75) {

            SCNNode *sub1 = [SCNNode nodeWithGeometry:shapeRed];

            [arcNode addChildNode:sub1];

            

            SCNNode *sub2 = [SCNNode nodeWithGeometry:shapeGreen];

            [arcNode addChildNode:sub2];

        }

    }

}

– (void)createCamera {

    SCNNode *camera = [SCNNode node];

    camera.camera = [SCNCamera camera];

    camera.position = SCNVector3Make(0, 0, 30);

    [self.sceneView.scene.rootNode addChildNode:camera];

}

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

{

    [self.sceneView.scene.rootNode.childNodes enumerateObjectsUsingBlock:^(SCNNode *n, NSUInteger idx, BOOL *stop) {

        if ([n.name hasPrefix:@”no”] && [[n.name substringFromIndex:2] intValue] >= 75) {

            [n runAction:[SCNAction rotateToX:0 y:0 z:0 duration:1.0]];

        }

    }];

}

@end