帧速率受到CADisplayLink和drawRect的影响

问题描述 投票:3回答:1

我的问题是关于iOS开发。我正在编写一个简单的游戏,以测试低级Core Graphics函数(上下文,图层等)以及如何将它与实际的简单视图混合...我解释一下:我在屏幕上有一个简单的精灵,它是使用UIImageView属性进行动画处理,因此帧速率非常有效。在那之后,我添加了一个无限的背景,使用bezier curves即时生成。为了制作动画,我使用CADisplayLink,在背景上调用方法"animate",将我的点移动到bezier curve,然后我调用setNeedsDisplay。它“或多或少”工作得很好,但如果我删除背景(或setNeedsDisplay调用,因此它不会每帧重新生成)帧速率会增加很多,所以“任何东西”在这部分都无法正常工作。 。

我也尝试了一个双缓冲系统,但它比我目前的代码更糟糕。我虽然也使用了一个线程,但我真的没有找到任何难以让CPU在后台做的事情。

这是代码:

//This is called automatically with CADDisplayLink.
- (void) animate:(CADisplayLink *)sender
{
    //Check for deleting the first point.
    float x = points[firstPoint].x;
    if ( x < -2*DIST ) {
        CGFloat lastX = points[lastPoint].x;
        lastPoint = firstPoint;
        firstPoint = ((firstPoint + 1) % (TOTAL_POINTS));
        points[lastPoint] = CGPointMake(lastX + DIST, [self getNextY]);
    }

    //Move points
    for(int i = 0; i < TOTAL_POINTS; i++) {
        points[i].x -= 7;
    }

    //Mark as "needed to redraw"
    [self setNeedsDisplay];

}

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

    CGContextSetLineWidth(context, 3.0);
    CGContextSetRGBStrokeColor(context, 0, 0, 0, 1.0);
    CGContextSetRGBFillColor(context, 1.0, 0, 0, 1.0);
    CGContextSetLineCap(context, kCGLineCapRound);

    //Create path
    CGMutablePathRef path = CGPathCreateMutable();

    //Draw the curve
    [self drawBezierCurveInPath:path];

    //Close and add path
    CGPathAddLineToPoint(path, NULL, 485, -5);
    CGPathAddLineToPoint(path, NULL, -5, -5);
    CGPathCloseSubpath(path);

    CGContextAddPath(context, path);

    CGContextSetFillColorWithColor(context, bg2);

    //    [[UIColor redColor] setFill];
    [[UIColor blackColor] setStroke];

    CGContextDrawPath(context, kCGPathFillStroke);    

    //Release
    CGPathRelease(path);

    //Paint time.
    playintIntervalView.text = [NSString stringWithFormat:@"%f", playingInterval];
}

- (void) drawBezierCurveInPath: (CGMutablePathRef) path
{
    CGPoint fp = midPoint(points[firstPoint], points[(firstPoint+1)%TOTAL_POINTS]);
    CGPathMoveToPoint(path, NULL, fp.x, fp.y);

    int i = firstPoint;
    for (int k = 0; k < TOTAL_POINTS-2; k++) {
        previousPoint2 = points[i];
        previousPoint1 = points[(i+1)%TOTAL_POINTS];
        currentPoint = points[(i+2)%TOTAL_POINTS];

        // calculate mid point
        CGPoint mid2 = midPoint(currentPoint, previousPoint1);

        CGPathAddQuadCurveToPoint(path, nil, previousPoint1.x, previousPoint1.y, mid2.x, mid2.y); 

        i = (i + 1) % TOTAL_POINTS;        
    }

}

我更喜欢存储一个UIBezierPath(所以我可以进行一些碰撞测试),但它不允许你只删除一个点(当它离开屏幕在左边),所以我必须每帧初始化它......我错过了什么吗?

iphone objective-c ios drawrect cadisplaylink
1个回答
2
投票

这可能有点晚了,但在这种情况下使用CADisplayLink来制作动画是一个坏主意。您应该查看CoreAnimation以获得有效的路径动画。

这里的问题是你试图每秒重绘60次,而drawRect中的代码可能没有在你拥有的毫秒内完成。通过删除setNeedsDisplay,你基本上告诉它不要更新。

© www.soinside.com 2019 - 2024. All rights reserved.