iPhone:旋转绘图而不旋转绘制绘图的视图
任何在 iTunes 上学过斯坦福 CS193P 课程的人都会从作业 3 (HelloPoly) 中认出这一点。对于那些不熟悉的人:
我有一个名为 polyView 的自定义视图,它是 PolygonView 的一个实例,是 UIView 的子类。在此视图上,我使用 CGContextDrawLinearGradient 在整个矩形视图上绘制颜色渐变。然后我使用 CGContextDrawPath 在 polyView 的边界内描边和填充多边形。我在视图(和多边形)的中心有一个名为 nameLabel 的 UILabel,它显示多边形的名称(三角形、四边形、五边形等)。所有这些都工作正常,并且执行所有这些操作的代码位于 PolygonView 类的 -(void)drawRect 方法中。
我遇到麻烦的地方是需要在视图内旋转多边形以响应用户手势。我使用 CGAffineTransformRotate() 来响应 PolygonView 类中的touchesBegan() 和touchesMoved() 事件,这基本上也有效。但我只能旋转整个polyView,而不仅仅是在其上绘制的多边形。我确信我可以返回并重新计算多边形的路径并重新绘制/填充路径以响应每个 TouchMoved() 事件,但这会很昂贵并且不是最好的方法。如何使用 CGAffineTransformRotate 仅旋转多边形,而不旋转渐变填充视图或中心的标签?
或者是否有某种方法可以在图层上创建多边形,我可以将其以所需的旋转角度放置在背景 polyView 上?
感谢您在这里为初学者提供的任何帮助!
杜安
Anyone who has gone through the Stanford CS193P class on iTunes will recognize this from Assignment 3 (HelloPoly). For those not familiar:
I have a custom view called polyView, an instance of PolygonView, a subclass of UIView. On this view, I use CGContextDrawLinearGradient to paint a color gradient over the entire rectangular view. Then I use CGContextDrawPath to stroke and fill a polygon within the bounds of polyView. And I have a UILabel called nameLabel in the center of the view (and polygon) that displays the name of the polygon (triangle, quadrilateral, pentagon, etc.). All of this works fine, and the code to do all this is in the -(void)drawRect method of the PolygonView class.
Where I ran into trouble is with an additional requirement to rotate the polygon within the view in response to user gestures. I used CGAffineTransformRotate() in response to touchesBegan() and touchesMoved() events within the PolygonView class, and this basically works, too. But I can only rotate the entire polyView, not just the polygon drawn on it. I'm sure I could go back and recalculate the path of the polygon and redraw/fill the path in response to each touchesMoved() event, but that would be expensive and can't be the best method. How can I use CGAffineTransformRotate to rotate just the polygon, without rotating the gradient-filled view or the label in the center?
Or is there some way to create the polygon on a layer that I can place over the background polyView at the desired rotation angle?
Thanks for any help you can give a beginner here!
Duane
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在进行旋转变换之前执行 CGContextSaveGState(...) ,然后绘制多边形并在之后使用 CGContextRestoreGState(...) 恢复绘制状态,以免影响视图中的任何其他绘制。
You can do a CGContextSaveGState(...) just before doing the rotation transformation, then drawing the polygon and restoring the drawing state with a CGContextRestoreGState(...) afterwards, so as not to affect any other drawing in the view later.