使用Quartz绘制线图?

时间:2013-03-30 13:14:44

标签: ios ios6 quartz-graphics

我正在尝试为ipad制作一个简单的图表。我需要使用QUARTZ绘制sin(x),cos(x)和tan(x)函数。我知道如何制作网格和线条,但不知道如何从这开始。任何帮助表示赞赏。

请注意我对核心情节和其他框架不感兴趣,所以请不要将此作为答案。

1 个答案:

答案 0 :(得分:2)

简单:你决定你想要什么样的分辨率/精度,然后根据它将函数的域分成间隔,你计算每个区间中函数的值,然后用直线连接它们:

// Within a subclass of UIView
- (void)drawFunction:(double (*)(double))fn from:(double)x1 to:(double)x2
{
    [super drawRect:rect];

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGFloat comps[] = { 1.0, 0.0, 0.0, 1.0 };
    CGContextSetStrokeColor(ctx, comps);
    CGContextSetLineWidth(ctx, 2.0);

    const double dx = 0.01; // precision
    double scale_x = self.bounds.size.width / (x2 - x1);
    double off_x = 0.0;
    double scale_y = scale_x;
    double off_y = self.bounds.size.height / 2;

    CGContextMoveToPoint(ctx, x1 * scale_x - off_x, off_y - fn(x1) * scale_y);

    for (double x = x1 + dx; x <= x2; x += dx) {
        double y = fn(x);
        CGFloat xp = x * scale_x - off_x;
        CGFloat yp = off_y - y * scale_y;
        CGContextAddLineToPoint(ctx, xp, yp);
    }

    CGContextStrokePath(ctx);
}

- drawRect:

拨打此电话
- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    [self drawFunction:sin from:0.0 to: 2 * M_PI];
}