开发者

NStimer slow in device?

i have done following to translate background screen.view.m 开发者_如何学运维file.but the frame rate is very slow.i changed time interval with different value,but the image is translating very slowly in Iphone Device? any solution?pls?

 - (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
    // Initialization code
    x =0;

    xx = 0;
    yy = 0;
    secX = 0;

    [NSTimer scheduledTimerWithTimeInterval:(0.1/60) target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}
return self;

}

 -(void) onTimer
 {  
xx++;
xx = ( xx % 320);

[self setNeedsDisplay];

}



 - (void)drawRect:(CGRect)rect {
// Drawing code


[[UIImage imageNamed:@"graphic.png"] drawAtPoint:CGPointMake(yy,xx )];

if(xx >= 0)
{

    [[UIImage imageNamed:@"graphic.png"]  drawAtPoint:CGPointMake((-320 - (-1 * xx)),yy)];


}


You seem to be drawing the image each time in your drawRect method. I think if you used a UIImageView to hold the UIImage and just moved that it might be faster?

In your .h file

@property (nonatomic, retain) UIImageView *myImageView;

In your init method

self.myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"graphic.png"]] autorelease];

and in your timer callback just move the UIImageView like so

- (void) onTimer {
    xx++;
    xx = ( xx % 320);

    self.myImageView.center = CGPointMake(xx, self.myImageView.center.y);
}

(There is no need for a drawRect anymore)

Hope that helps,

Sam


NSTimer is working fine. Your problem is that drawing an image is a relatively processor intensive task and you are doing it 600 times a second. You're simply swamping the relatively slow processor on the iPhone.

You need to follow the previous advice and use an imageview or move the image to its own CALayer within the view. That way, you only draw the image once and then you can draw anything else in other layers.

Alternatively, you can create a UIImageView and then set other views as subviews. You then translate the imageview and draw into the subviews.

I can't think of any reason why drawing the image over and over again 600/sec in drawrect is the best way to go.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜