首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CGContextRef被腐蚀了吗?

CGContextRef被腐蚀了吗?
EN

Stack Overflow用户
提问于 2011-03-08 22:28:54
回答 1查看 551关注 0票数 2

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

代码语言:javascript
复制
- (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时得到的错误消息:Program received signal: “EXC_BAD_ACCESS”.

回答:,我需要在CGContextAddLineToPoint()周围设置一个守卫,以确保它在rect的范围内

代码语言:javascript
复制
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);
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-03-09 00:56:11

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

如果我不得不猜测的话,expressionForGraphView有时可能会返回垃圾。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5239165

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档