在单个上下文中以不同方向绘制多个对象
我正在尝试使用循环在单个 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
我很难让我的头脑围绕上下文移动。似乎更简单的解决方案是更改矩形方向。
任何帮助表示赞赏!
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);
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,您不能使用 CGContextAddRect() 方法以自定义方向绘制矩形。也许我错了,但我认为你必须使用以下方式绘制它们:
所以,你可能必须用自定义方法计算坐标。
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:
So, you'll probably have to calculate coordinates in a custom method.