So I have a class that returns a CALayer that has an array of CALayers added as sublayers, but the problem is that it doesn’t seem to be rendering any of them. I think I may just be missing something about how CALayers work as I’m not very familiar yet. Could someone please take a look at my code to see what I am doing wrong?
- (CALayer*)drawMap {
CALayer* theLayer = [CALayer layer];
for (int y = 0; y < [self.height intValue]; y++) {
for (int x = 0; x < [self.width intValue]; x++) {
CALayer* tileLayer = [CALayer layer];
tileLayer.bounds = CGRectMake((x * [self.tileWidth intValue]), (y * [self.tileHeight intValue]), [self.tileWidth intValue], [self.tileHeight intValue]);
[tileLayer setBackgroundColor:[UIColor colorWithHue:(CGFloat)x saturation:(CGFloat)y brightness:255 alpha:1.0].CGColor];
[theLayer addSublayer:tileLayer];
}
}
[theLayer setBounds:CGRectMake([self.width intValue] * [self.tileWidth intValue], [self.height intValue] * [self.tileHeight intValue], 10, 10)];
return theLayer;
}
This is the code that initializes and draws the map.
Map* myMap = [[Map alloc] initFromFile];
[myMap setWidth:[NSNumber numberWithInt:100]];
[myMap setHeight:[NSNumber numberWithInt:100]];
[self.view.layer insertSublayer:[myMap drawMap] above:self.view.layer];
I can provide the headers if needed, but I don’t think the problem is there and I don’t want a huge post.
I think the problem is the bounds you’re setting to your parent layer:
That would appear to set the bounds so that it starts just exactly past all the sublayers you’ve just added and extends for 10 points in both directions. I think the following would be more appropriate:
The following also looks fishy:
[myMap drawMap]will become a sublayer ofself.view.layer.self.view.layeris not one of its own subviews so it won’t know what to do with thatabove:instruction. You probably want justaddSublayer:.Finally, this:
gives every single one of your sublayers exactly the same
frame. Much likeUIViews, theboundsare the source area for information and the frame is where that information will be put within the super layer. I think probably you want to setframe.Finally,
UIColor +colorWithHue:...clamps hue and saturation to the range [0, 1] so you probably want(CGFloat)x / [self.width floatValue]and the equivalent for saturation to ensure all your tiles come out in different colours.EDIT: so, tying all that together, I modified your code slightly so that I didn’t have to write the full encompassing class and added it to the Xcode view-based project template as follows:
That gives the hue/saturation plane familiar from many an art package.