使用Quartz通过NSTimer(iPhone)每秒进行绘制 [英] Using Quartz to draw every second via NSTimer (iPhone)

查看:71
本文介绍了使用Quartz通过NSTimer(iPhone)每秒进行绘制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相对不熟悉Objective-C + Quartz,并且遇到了一个可能很简单的问题。我有一个自定义UIView子类,该类用于通过Quartz绘制简单的矩形。但是我试图连接一个NSTimer,以便它每秒绘制一个新对象,下面的代码将绘制第一个矩形,但将不再绘制。正在调用该函数(运行了NSLog),但未绘制任何内容。

I'm relatively new to Objective-C + Quartz and am running into what is probably a very simple issue. I have a custom UIView sub class which I am using to draw simple rectangles via Quartz. However I am trying to hook up an NSTimer so that it draws a new object every second, the below code will draw the first rectangle but will never draw again. The function is being called (the NSLog is run) but nothing is draw.

代码:

- (void)drawRect:(CGRect)rect {
    context = UIGraphicsGetCurrentContext();

    [self step:self];
    [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)(2) target:self selector:@selector(step:) userInfo:nil repeats:TRUE];

}

- (void) step:(id) sender {
    static double trans = 0.5f;

    CGContextSetRGBFillColor(context, 1, 0, 0, trans);
    CGContextAddRect(context, CGRectMake(10, 10, 10, 10));
    CGContextFillPath(context);

    NSLog(@"Trans: %f", trans);

    trans += 0.01;
}

上下文在我的界面文件中为:

context is in my interface file as:

CGContextRef context;

任何帮助将不胜感激!

推荐答案

您的示例不起作用。原因是 drawRect:在视图需要绘制时被调用,并且它不能自己绘制。

Your example won't work. The reason is that drawRect: is called for you when the view requires drawing, and it can't draw on its own.

相反,请尝试在 drawRect:之外使用计时器(想到的是 viewDidLoad ),每个一次添加一个对象以绘制到列表中,然后调用 [view setNeedsDisplay] 来请求重画该对象。如果您需要更严格的控制,还有其他技术,但是最好先掌握应用程序流程的基础。

Instead, try using your timer from outside of drawRect: (viewDidLoad comes to mind), and each time add an object to draw to a list, and call [view setNeedsDisplay] to request it to be redrawn. There are other techniques if you need stricter control, but it's a good idea to master the basics of application flow first.

这篇关于使用Quartz通过NSTimer(iPhone)每秒进行绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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