ios - cgcontext 旋转矩形

标签 ios rotation core-graphics cgcontext rect

伙计们! 我需要绘制一些图像到 CGContext。这是相关代码:

CGContextSaveGState(UIGraphicsGetCurrentContext());

CGContextRef ctx = UIGraphicsGetCurrentContext();

CGRect rect = r;

CGContextRotateCTM(ctx, DEGREES_TO_RADIANS(350));
[image drawInRect:r];


CGContextRestoreGState(UIGraphicsGetCurrentContext());

实际上,矩形是旋转并显示在一个区域上,这不是我的目的。我只是想 旋转图像并显示在同一位置。 有什么想法吗?????

最佳答案

旋转是关于上下文的原点,这是矩形相对于的同一个点。如果您想象背景中有一张方格纸,您可以更清楚地看到发生了什么:

Rotated context with graph-paper grid in the background and rectangle in the foreground

该线是窗口/ View /层/上下文的“底部”(y=0)。当然,如果你愿意,你可以在底部下方绘制,如果你的上下文以正确的方式转换,你甚至可以看到它。

无论如何,我假设您想要做的是相对于未旋转的世界旋转矩形,而不是旋转世界和其中的所有内容。

旋转任何东西的唯一方法就是旋转世界,所以这就是你需要做的:

  1. 保存图形状态。

  2. 将原点平移到要绘制矩形的点。 (您可能想平移到它的中心点,而不是矩形的原点。)

    Translated context with graph-paper background, showing the origin at what will be the center of the rectangle

  3. 旋转上下文。

    Translated and rotated context with graph-paper background, showing that the axes have now tilted up as before, but now the translated origin has also moved just as the rectangle did

  4. 绘制以原点为中心的矩形。换句话说,矩形的原点应该是宽度的负一半和高度的负一半(即 (CGPoint){ width/-2.0, height/-2.0 })——不要使用origin 它以前有,因为您已经在翻译步骤中使用了它。

    Rectangle drawn in its position, with graph-paper background and origin lines removed

  5. 恢复 gstate,这样以后的绘图就不会旋转。

关于ios - cgcontext 旋转矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15696850/

相关文章:

opencv - 将 opencv 仿射矩阵转换为 CGAffineTransform

rotation - 如何将 2 个四元数旋转回起始位置,然后计算相对旋转?

iphone - 当 ClipToBounds=NO 时不绘制外部边界

iphone - 将 UIImage 用于 CGContextSetFillColorWithColor 时突然出现内存峰值

objective-c - 子类化UIButton,但是我无法执行“addTarget:action:forControlEvents:”吗?

iphone - 在网格上旋转 CGPoint 的最佳方法是什么?

java - 从起始坐标、角度和距离获取点

ios - 我们对 Touch ID For iOS 有任何值(value)吗?

ios - 安装企业 iOS 应用程序时出现 "Untrusted App Developer"消息

ios - 如何从 NSArray 中提取数组?