gpt4 book ai didi

iphone - 帧速率与 CADisplayLink 和 drawRect 妥协

转载 作者:搜寻专家 更新时间:2023-10-30 20:20:26 25 4
gpt4 key购买 nike

我的问题是关于 iOS 开发的。我正在编写一个简单的游戏,以测试低级核心图形功能(上下文、图层等)以及如何将它与实际的简单 View 混合......我解释一下:我在屏幕上有一个简单的 sprite,它使用 UIImageView 属性进行动画处理,因此帧速率完美运行。之后,我添加了一个使用 bezier 曲线 动态生成的无限背景。为了制作动画,我使用了 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(这样我就可以进行一些碰撞测试)但它不允许你只删除一个点(当它离开屏幕左侧时),所以我也必须在每一帧都初始化它……我错过了什么吗?

最佳答案

这可能有点晚了,但在这种情况下使用 CADisplayLink 制作动画并不是一个好主意。您应该研究 CoreAnimation 以获得高效的路径动画。

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

关于iphone - 帧速率与 CADisplayLink 和 drawRect 妥协,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12925959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com