Question

When I resize a window containing about 10,000 CATextLayers, the initial resizing freezes the window for a few seconds. After the initial freeze, resizing stutters noticeably.

Profiling and common sense suggest that this is slow because of all the internal redrawing (apparently CATextLayers use Core Text under the hood).

What optimizations (if any) can be done to make resizing a window with 10,000 text layers fast and efficient?

Here's the code I use to create the layers, in a simple NSView subclass:

- (id) initWithFrame:(NSRect)frameRect {
    if (self = [super initWithFrame:frameRect]) {
        [self setLayer:[CALayer layer]];
        [self setWantsLayer:YES];
    }
    return self;
}

- (void) awakeFromNib {
    [super awakeFromNib];

    int w = 8;
    int h = 14;

    self.layer.backgroundColor = [NSColor whiteColor].CGColor;

    for (int y = 0; y < 100; y++) {
        for (int x = 0; x < 100; x++) {
            CATextLayer* t = [CATextLayer layer];
            t.opaque = YES;
            t.frame = NSMakeRect(x * w, y * h, w, h);
            t.foregroundColor = [NSColor blackColor].CGColor;
            t.backgroundColor = [NSColor yellowColor].CGColor;
            t.string = @"a";
            t.font = (__bridge CGFontRef)[NSFont fontWithName:@"Menlo" size:12];
            t.fontSize = 12;
            [self.layer addSublayer:t];
        }
    }
}

For more context: I'm creating a text grid where each cell's character, text color, and background color can be changed (kind of like Terminal.app).

For this reason, the one optimization I've thought of, which is to use a single CATextLayer per line, rather than per "cell", won't work, because a single CATextLayer can only have one foreground color and one background color.

Was it helpful?

Solution

You can try to approach this problem as follows:

The drawback is that the resizing in progress looks somewhat pixelated. In addition, rendering 10K layers onto a bitmap may be time-consuming.

The advantage is that once the rendering is complete, resizing is fast and smooth.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top