Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mirror a UIBezierPath?

I have a UIBezierPath and I would like to get its mirror image. How can I accomplish this?

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

 // ? now I would like to mirror myPath ?
like image 253
wfbarksdale Avatar asked Jan 06 '14 20:01

wfbarksdale


2 Answers

It should be noted that you might need additional code depending on where in the overall view the path you are trying to mirror is.

If you are trying to mirror a path that takes up the whole view (or is at least flush with the 0 coordinate of the axis you are mirroring over), then @wbarksdale's answer will work for you. However, if you are trying to mirror a path thats a small section of the overall view thats somewhere in the middle of the view, then you need to do more work. In general, the algorithm is like this

  //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))

In general, the algorithm should be

  1. Move the path either to the very left or the very top of the view depending on whether you are flipping horizontally or vertically, using CGAffineTransform(translateX....)

  2. Mirror the view using CGAffineTransform(scaleX....

  3. Move the view back to its original position using CGAffineTransform(translateX....)

like image 63
gregkerzhner Avatar answered Nov 01 '22 01:11

gregkerzhner


// 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];
like image 34
wfbarksdale Avatar answered Nov 01 '22 02:11

wfbarksdale