gpt4 book ai didi

iphone - CGContextRef 损坏了吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:57:23 26 4
gpt4 key购买 nike

当我调用函数 CGContextStrokePath(下面代码的最后一行)时,我的程序崩溃了。上下文是否会以某种方式损坏? (它只有在 expression(它是一个 NSArray)中有特定值时才会崩溃)。它应该绘制 expression 中的任何内容的图表。例如,如果 expression 具有以下对象:x, cos(表示为字符串),它将绘制余弦曲线。这是代码:

- (double) yValueFromExpression:(id)anExpression atPosition:(double)xValue
{
NSDictionary *aDictionary = [NSDictionary dictionaryWithObject:[NSNumber numberWithDouble:xValue] forKey:@"%x"];
return [CalculatorBrain evaluateExpression:anExpression usingVariableValues:aDictionary];
}

#define PRECISION 500

- (void)drawRect:(CGRect)rect
{
double scale = [self.delegate scaleForGraphView:self];
id expression = [self.delegate expressionForGraphView:self];

CGPoint origin;
origin.x = (self.bounds.origin.x + self.bounds.size.width) / 2;
origin.y = (self.bounds.origin.y + self.bounds.size.height) / 2;

[AxesDrawer drawAxesInRect:self.bounds originAtPoint:origin scale:scale];

// -150/scale to 150/scale is the range of x values that axesDrawer (drawAxesInRect) displays.
double leftMostXValue = -150 / scale;
double rightMostXValue = 150 / scale;
double increment = (rightMostXValue - leftMostXValue) / PRECISION;

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextBeginPath(context);
CGContextMoveToPoint(context, self.bounds.origin.x, origin.y -
[self yValueFromExpression:expression atPosition:leftMostXValue] * scale);

for (int i = 1; i <= PRECISION; ++i) {
double currentXValue = leftMostXValue + i * increment;
CGContextAddLineToPoint(context, self.bounds.origin.x + (self.bounds.size.width / PRECISION) * i,
origin.y - [self yValueFromExpression:expression atPosition:currentXValue] * scale);
}
CGContextStrokePath(context);
}

这是我在调用 CGContextStrokePath 时收到的错误消息:程序收到信号:“EXC_BAD_ACCESS”。

答案:我需要在 CGContextAddLineToPoint() 周围放置一个保护装置,以确保它在 rect 的范围内绘制:

for (int i = 1; i <= PRECISION; ++i) {
double currentXValue = leftMostXValue + i * increment;
double xPoint = self.bounds.origin.x + (self.bounds.size.width / PRECISION) * i;
double yPoint = origin.y - [self yValueFromExpression:expression atPosition:currentXValue] * scale;
if (xPoint < (self.bounds.origin.x + self.bounds.size.width) && xPoint > 0 &&
yPoint < (self.bounds.origin.y + self.bounds.size.height) && yPoint > 0) {
CGContextAddLineToPoint(context, xPoint, yPoint);
}
}

最佳答案

EXC_BAD_ACCESS 通常意味着你有内存问题。

如果非要我猜的话,expressionForGraphView 有时可能会返回垃圾。

关于iphone - CGContextRef 损坏了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5239165/

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