I have a regular SpriteKit scene. In fact it is the default scene created from "Sprite Kit" which draws spaceships.
I would like to draw on the background.
I have successfully added a UIImageView as a subview of the main skView. I can draw on this with lines and such.
But I can't seem to succesfully put the UIImageView behind the main skview.
How can I do this? Here is my sample code.
(In the UIImageView I'm just drawing random lines every 0.1 seconds.)
@implementation GameViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Configure the view.
SKView * skView = (SKView *)self.view;
// skView.showsFPS = YES;
// skView.showsNodeCount = YES;
/* Sprite Kit applies additional optimizations to improve rendering performance */
//skView.ignoresSiblingOrder = YES;
// Create and configure the scene.
GameScene *scene = [GameScene unarchiveFromFile:@"GameScene"];
scene.scaleMode = SKSceneScaleModeAspectFill;
[skView presentScene:scene];
}
-(void)viewWillLayoutSubviews{
self.imageView = [UIImageView new];
self.imageView.frame = self.view.frame;
[self.view addSubview:self.imageView];
[self startRepeatingTimer];
}
-(void)viewDidLayoutSubviews{
// this doesn't work. was just trying it out.
int i = [[self.view subviews] count];
[self.view exchangeSubviewAtIndex:0 withSubviewAtIndex:i-1];
}
///// DRAW RANDOM LINES EVERY 0.1 SECONDS ON THE UIIMAGEVIEW SUBVIEW
- (IBAction)startRepeatingTimer {
[self.repeatingTimer invalidate];
self.repeatingTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(drawOnImage:) userInfo:nil repeats:YES];
}
- (void)drawOnImage:(NSTimer*)theTimer {
//setup
float w = self.view.frame.size.width;
float h = self.view.frame.size.height;
UIGraphicsBeginImageContextWithOptions(self.view.frame.size,NO,0.0);
[self.imageView.image drawInRect:CGRectMake(0, 0, w, h)];
CGContextRef c = UIGraphicsGetCurrentContext();
//draw
CGContextMoveToPoint(c, drand48()*w,drand48()*h);
CGContextAddLineToPoint(c, drand48()*w,drand48()*h);
CGContextSetLineCap(c, kCGLineCapRound);
CGContextSetLineWidth(c, 1.0f );
CGContextSetRGBStrokeColor(c, drand48(), drand48(), drand48(), 1.0);
CGContextStrokePath(c);
// set the image
self.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}