首页 文章

基准UIView drawRect:方法

提问于
浏览
6

我在Objective-C中编写了一个iPhone应用程序,它在视图中使用了一些自定义绘图,我想对我的代码的各种修订进行基准测试,看看它真正有用 . 我正在计划这样做,通过设置一个新的应用程序,将我的自定义绘图代码添加到视图的drawRect:方法,然后,在视图控制器的for循环中,发送 [UIView setNeedsDisplay] 一些很多次并计时多长时间需要完成 . 但是 setNeedsDisplay 调用似乎是缓存的,所以即使我在for循环中调用它1000次, drawRect: 方法只被调用一次 . 此外,我尝试直接调用drawRect:但我需要一个图形上下文来做一些绘图,当我不使用 setNeedsDisplay: 时,UIGraphicsGetCurrentContext()不会给我一个上下文 .

有什么建议?

谢谢,

凯尔

4 回答

  • 0

    您可以通过执行以下操作来为视图 Build 基准:

    - (NSTimeInterval)timeTakenToDrawView:(UIView *)view count:(NSInteger)count
    {
        CGRect bounds = [view bounds];
        NSDate *startDate = [NSDate date];
        UIGraphicsBeginImageContext(bounds.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        NSInteger i = 0;
        for (i = 0; i < count; i++) {
            CGContextSaveGState(context);
            [view drawRect:bounds];
            CGContextRestoreGState(context);
        }
        UIGraphicsEndImageContext();
        return [[NSDate date] timeIntervalSinceDate:startDate];
    }
    

    (没试过,但它应该工作)

  • 5

    你的NSView的.m内部 . 显然,您可能希望将其连接到UI或其他内容 .

    - (void)awakeFromNib {
        // Have to wait for the window to be onscreen, graphics context ready, etc
        [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFired:) userInfo:NULL repeats:NO];
    }
    
    
    - (void)timerFired:(NSTimer *)aTimer {
        [self lockFocus];
    
        NSDate* then = [NSDate date];
    
        int callIdx = 0;
        for( callIdx = 0; callIdx < 1000; callIdx++ ) {
            [self drawRect:[self bounds]];
        }
        NSDate* now = [NSDate date];
    
        [self unlockFocus];
    
        NSLog(@"Took %f seconds", [now timeIntervalSinceDate:then]);
    }
    
    - (void)drawRect:(NSRect)rect {
        [[NSColor redColor] set];
        NSRectFill(rect);
    }
    
  • 0

    不要忘记,如果经常使用drawRect,您也可以使用CoreImage性能工具并获得帧率 .

    您还可以使用一些性能工具来查看该方法花费的时间 .

  • 0

    如果您正在寻找可以进行更深入分析的内容,我可以使用一组宏来进行时间分析:https://gist.github.com/952456

相关问题