Change .contents of sublayers in a NSMutablearray

2019-09-19 04:59发布

问题:

I am creating a 96x 64 grid of sublayers once,so i can easily update their .contents...

- (void)createLayer{
    CALayer *currentLayer = self.layer;

    _layerArray = [[NSMutableArray alloc] initWithCapacity:WIDTH*HEIGHT];
    int cellSize = self.bounds.size.width / WIDTH;
    double xOffset = 0;

    CGRect cellFrame = CGRectMake(0, 0, cellSize, cellSize);
    NSUInteger cellIndex = 0;
    cellFrame.origin.x = xOffset;

    for (int i = 0; i < WIDTH; i++)
    {
        cellFrame.origin.y = 0;
        for (int j = 0; j < HEIGHT; j++, cellIndex++)
        {                
            if([[self.levelState.boardChanges objectAtIndex:(i*HEIGHT)+j] intValue]==1){
                {
                    NSNumber *currentCell = [self.levelState.board objectAtIndex:cellIndex];
                    CALayer *sublayer = [CALayer layer];
                    sublayer.frame = cellFrame;
                    if (currentCell.intValue == 1)
                    {
                        sublayer.contents = (id) [UIImage imageNamed:@"image1.png"].CGImage;
                    }
                    else if (currentCell.intValue == 0)
                    {
                        sublayer.contents = (id) [UIImage imageNamed:@"image2.png"].CGImage;
                    }
                    [currentLayer addSublayer:sublayer];
                    [_layerArray addObject:sublayer];
                }
            }
            cellFrame.origin.y += cellSize;
        }
        cellFrame.origin.x += cellSize;
    }
}

However i fail at exactly that.. what i tried is something like that...

[[_layerArray objectAtIndex:(i*HEIGHT)+j ].contents ] = (id) [UIImage imageNamed:@"image.png"].CGImage;

How do i change their .contents ? Should i use NSArray instead ?

Thank you !

回答1:

I haven't tested this, but it looks as though it would work

[sublayer.contents addObject:[UIImage imageNamed:@"image2.png"]];


回答2:

[[_layerArray objectAtIndex:(i*HEIGHT)+j ] setContents:(id) [UIImage imageNamed:@"image.png"].CGImage];

But its very slow...

### final edit

the approach posted as topic above was much to slow... my final approach is the following:

UIViewController has UIView has CALayers as sublayers

Sublayers are: 1. The background at zindex 0 2. The frontImages which are blended images of sorts at higher zindexes....