开发者

Drawing multiple objects on a single context with different orientations

I am trying to draw a bunch of rectangles (up to 2000) on a single UIView using a loop. I can achieve this quite easily with the following code in the DrawRect method of the UIView:

CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetLineWidth(context, 1.0);
    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
开发者_C百科    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];
    }

However, each of my rectangles can have a different orientation which is represented by an angle (i degrees). For the life of me I cannot figure out how to draw each shape with its own independent orientation, any ideas?

I've tried the following code, but it doesn't seem to work.

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

I'm having trouble getting my head around the context moving. Seems a much simpler solution would be to change the rectangle orientation.

Any help appreciated!


According to me, you can't use CGContextAddRect() method to draw a rectangle in a custom orientation. Maybe i'm wrong but i think that you have to draw them by using:

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

So, you'll probably have to calculate coordinates in a custom method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜