在Objective C中非常有效地绘制了许多字符串

时间:2014-10-10 14:53:38

标签: ios objective-c cocoa-touch uikit

在占据整个屏幕的UIView中,我需要在里面绘制几百个带有文本的矩形。

UIView对平移和捏合,移动和缩放矩形做出反应。 文本字体根据缩放而变化。

我需要一种非常快速的方法来绘制矩形内的字符串。到目前为止我发现的太慢了。

我添加了一个测试示例,一个UIView的drawRect,没有缩放变得简单。在iPad2上绘制矩形需要约0.5秒,这是一个漫长的等待。

- (void)drawRect:(CGRect)rect
{
    // Prepare the rectangles in which to draw the strings
    // in the real app the size of the rectangles will change according to the zooming
    // this takes very little time
    CGRect rectangles[600] ;
    float width = self.frame.size.width / 20.;
    float height = self.frame.size.height / 30.;
    int k = 0;
    for (int i = 0; i < 20; i++) 
    {
        for (int j = 0; j < 30; j++) 
        {
            rectangles[k] = CGRectMake(i * width , j * height, width, height);
            k++;
        }
    }


    // In the real app, the font size will change according to the zooming
    // it cannot be stored once for all
    float txtSize = self.frame.size.width / 30. / 4;

    NSDictionary *attributesTitle = @{NSFontAttributeName: [UIFont fontWithName:@"Verdana-bold" size:txtSize],
                                      NSForegroundColorAttributeName: [UIColor blackColor]};
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"Verdana" size:txtSize],
                                 NSForegroundColorAttributeName: [UIColor blackColor]};


    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    NSTextContainer *textContainer = [[NSTextContainer alloc] init];
    [layoutManager addTextContainer:textContainer];
    NSTextStorage *textStorage ;

    NSRange glyphRange;

    NSLog(@"Before");
    for (int i = 0; i < 600; i++) 
    {
        // In the real app, the font size will change according to the zooming, then the textStorage is not 

        // first string with title
        textStorage = [ [NSTextStorage alloc] initWithString:[NSString stringWithFormat:@"A:%d", i] attributes:attributesTitle];
        [textStorage addLayoutManager:layoutManager];
        glyphRange  = [layoutManager  glyphRangeForTextContainer:textContainer];
        [layoutManager drawGlyphsForGlyphRange: glyphRange atPoint: rectangles[i].origin];
        // second string with subtitle
        textStorage = [ [NSTextStorage alloc] initWithString:[NSString stringWithFormat:@"B:%d", i] attributes:attributes];
        [textStorage addLayoutManager:layoutManager];
        glyphRange = [layoutManager  glyphRangeForTextContainer:textContainer];
        [layoutManager drawGlyphsForGlyphRange: glyphRange atPoint: CGPointMake(rectangles[i].origin.x, rectangles[i].origin.y + 10)];
    }
    NSLog(@"After");
}

在Android上我的表现更好,但我对Objective-C不太熟练

0 个答案:

没有答案