核心图形旋转矩形

7

使用这个公式,我得到了角度。

double rotateAngle = atan2(y,x)

使用这段代码,我可以绘制一个矩形。

CGRect rect = CGRectMake(x,y , width ,height);
CGContextAddRect(context, rect);
CGContextStrokePath(context);

如何将矩形绕角度旋转?
1个回答

29

这是实现该功能的方法:

CGContextSaveGState(context);

CGFloat halfWidth = width / 2.0;
CGFloat halfHeight = height / 2.0;
CGPoint center = CGPointMake(x + halfWidth, y + halfHeight);

// Move to the center of the rectangle:
CGContextTranslateCTM(context, center.x, center.y);
// Rotate:
CGContextRotateCTM(context, rotateAngle);
// Draw the rectangle centered about the center:
CGRect rect = CGRectMake(-halfWidth, -halfHeight, width, height);
CGContextAddRect(context, rect);
CGContextStrokePath(context);

CGContextRestoreGState(context);

5
好的。由于用户1125890似乎有更重要的事情要做,所以管理员应该将此标记为已接受。我自己永远无法想出这个答案。谢谢! - Accatyyc
你救了我的命,兄弟。我尝试根据我的 superview 标签大小旋转我的矩形,但是最近几天一直越来越暗淡。但是你的解决方案像魔法一样奏效。非常感谢。 - Amrit Trivedi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接