如何镜像UIBezierPath?

时间:2014-01-06 20:11:48

标签: ios objective-c core-graphics uibezierpath

我有一个UIBezierPath,我希望得到它的镜像。我怎么能做到这一点?

 // Method for generating a path
 UIBezierPath *myPath = [self generateAPathInBounds:boundingRect];

 // ? now I would like to mirror myPath ?

3 个答案:

答案 0 :(得分:24)

// Method for generating a path
UIBezierPath *myPath = [self generateAPathInBounds:boundingRect];

// Create two transforms, one to mirror across the x axis, and one to
// to translate the resulting path back into the desired boundingRect
CGAffineTransform mirrorOverXOrigin = CGAffineTransformMakeScale(-1.0f, 1.0f);
CGAffineTransform translate = CGAffineTransformMakeTranslation(boundingRect.width, 0);

// Apply these transforms to the path
[myPath applyTransform:mirrorOverXOrigin];
[myPath applyTransform:translate];

答案 1 :(得分:1)

应该注意的是,您可能需要额外的代码,具体取决于您尝试镜像的路径在整个视图中的位置。

如果您正在尝试镜像占据整个视图的路径(或者至少与您正在镜像的轴的0坐标齐平),那么@ wbarksdale的答案将适合您。但是,如果您尝试镜像视图中间某处的整个视图的一小部分路径,那么您需要做更多工作。一般来说,算法就像这样

  //this rect should be the bounds of your path within its superviews
  //coordinate system
  let rect = myPath.bounds
  //first, you need to move the view all the way to the left
  //because otherwise, if you mirror it in its current position, 
  //the view will be thrown way off screen to the left
  path.apply(CGAffineTransform(translationX: -rect.origin.x, y: 0))
  //then you mirror it
  path.apply(CGAffineTransform(scaleX: -1, y: 1))
  //then, after its mirrored, move it back to its original position
  path.apply(CGAffineTransform(translationX: rect.origin.x + rect.width, y: 0))

一般来说,算法应该是

  1. 将路径移动到视图的最左侧或最顶部 取决于您是使用CGAffineTransform(translateX....)

  2. 水平还是垂直翻转
  3. 使用CGAffineTransform(scaleX....

  4. 镜像视图
  5. 使用CGAffineTransform(translateX....)

  6. 将视图移回原始位置

答案 2 :(得分:-2)

我认为您的path不以(0,0)为中心,此代码是正确的:

// Method for generating a path
UIBezierPath *myPath = [self generateAPathInBounds:boundingRect];

// Create two transforms, one to mirror across the x axis, and one to
// to translate the resulting path back into the desired boundingRect
CGAffineTransform mirrorOverXOrigin = CGAffineTransformMakeScale(-1.0f, 1.0f);
CGAffineTransform translate = CGAffineTransformMakeTranslation(CGRectGetMidX(boundingRect), 0);
CGAffineTransform translateBack = CGAffineTransformMakeTranslation(-CGRectGetMidX(boundingRect), 0);

// Apply these transforms to the path
[myPath applyTransform:translate];
[myPath applyTransform:mirrorOverXOrigin];
[myPath applyTransform:translateBack];