在具有不同方向的单个上下文中绘制多个对象

时间:2010-12-09 16:03:00

标签: iphone uiview core-graphics orientation

我试图使用循环在单个UIView上绘制一堆矩形(最多2000个)。我可以使用UIView的DrawRect方法中的以下代码轻松实现这一点:

CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetLineWidth(context, 1.0);
    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
    CGContextSetFillColorWithColor(context, [UIColor tescoBlue].CGColor);

    for (NSDictionary *dict in storeDimensionsArray) {
        float x = [[dict objectForKey:@"X"] floatValue];
        float y = [[dict objectForKey:@"Y"] floatValue];
        float width = [[dict objectForKey:@"Width"] floatValue];
        float length = [[dict objectForKey:@"Length"] floatValue];

        CGContextAddRect(context, CGRectMake(x, y, length, width));
        CGContextDrawPath(context, kCGPathFillStroke);
        [self setNeedsDisplay];
    }

然而,我的每个矩形都可以有不同的方向,由角度(i度)表示。对于我的生活,我无法弄清楚如何用自己独立的方向绘制每个形状,任何想法?

我已尝试过以下代码,但似乎无效。

    CGContextTranslateCTM (context, x, y);
    CGContextRotateCTM(context, radians([[dict objectForKey:@"Angle"] floatValue]));
    // tried adding the drawing code here 
    CGContextTranslateCTM (context, -x , -y);
    // ...or here

我无法理解上下文的动态。似乎更简单的解决方案是改变矩形方向。

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

据我所知,你不能使用CGContextAddRect()方法在自定义方向上绘制一个矩形。也许我错了,但我认为你必须使用以下方式绘制它们:

CGContextMoveToPoint(context, x, y);
CGContextAddLineToPoint(context, x, y);
CGContextAddLineToPoint(context, x, y);
CGContextAddLineToPoint(context, x, y);
CGContextAddLineToPoint(context, x, y);
CGContextStrokePath(context);

因此,您可能必须在自定义方法中计算坐标。

相关问题