在NSView中绘制多个线程 [英] Multiple threads to draw in NSView

查看:107
本文介绍了在NSView中绘制多个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我将NSView子类化,并在其drawRect方法中生成了三个线程来执行绘图.

In my code, I subclassed NSView and in its drawRect method, I am spawning three threads to perform the drawing.

-(void)drawRect:(NSRect)dirtyRect
{
    [[self window] setAllowsConcurrentViewDrawing:YES];
    [self setCanDrawConcurrently:YES];

    [NSThread detachNewThreadSelector:@selector(DrawText) toTarget:self withObject:nil];
    [NSThread detachNewThreadSelector:@selector(DrawRectangle) toTarget:self withObject:nil];
    [NSThread detachNewThreadSelector:@selector(DrawGradient) toTarget:self withObject:nil];

    //Wherease these functions DrawText, DrawRectangle and DrawGradient performs their task as suggested by name.

    //In DrawText, DrawRectangle, and DrawGradient lockFocus and unlockFocus is being
    // used for multithreaded drawing.

}

当我从Xcode运行相同的程序时,它运行良好.输出如下所示.

When I run the same program from Xcode, it is running fine. Output is shown below.

但是当我从外面运行它时,出现了问题,输出如下所示.

But when I run it from the outside, there is problem and output is shown below.

首先,我想知道从辅助线程进行绘制的正确方法吗?还是从辅助线程绘制的另一种方法是什么?

First, I would like to know is it right way to draw from a secondary thread? Or what is another way to draw from a secondary thread?

此问题背后的原因是什么?

What is the reason behind this problem?

推荐答案

我在NSGraphicsContext Restriction的信息/ThreadSafetySummary/ThreadSafetySummary.html#//apple_ref/doc/uid/10000057i-CH12-123364"rel =" nofollow>线程指南.

I read about NSGraphicsContext Restriction at Thread guide.

在这里,我找到了以下行:

Here, I found the following line:

如果从辅助线程进行任何绘图,则必须手动刷新绘图调用. Cocoa不会自动使用从辅助线程绘制的内容来更新视图,因此完成绘制时需要调用NSGraphicsContext的flushGraphics方法.如果您的应用程序仅从主线程绘制内容,则无需刷新绘制调用.

If you do any drawing from a secondary thread, you must flush your drawing calls manually. Cocoa does not automatically update views with content drawn from secondary threads, so you need to call the flushGraphics method of NSGraphicsContext when you finish your drawing. If your application draws content from the main thread only, you do not need to flush your drawing calls.

调用flushGraphics后,它可以正常工作.

After calling flushGraphics, it works fine.

这篇关于在NSView中绘制多个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆