3

I am drawing polygon using CGPath and adding to CAShapeLayer.I want to scale my CGPath when user click on it. I know how to scale CGPath. But when i click my CGPath, my CGPath drawing far from centre while i am drawing polygon in centre.

CGAffineTransform scaleTransform = CGAffineTransformMakeScale(scaleFactor, scaleFactor);
CGPathRef oldPath = polygonLayer.path;
CGPathRef scaledPath = CGPathCreateCopyByTransformingPath(oldPath, &scaleTransform);
polygonLayer.path = scaledPath;
rmaddy
  • 314,917
  • 42
  • 532
  • 579
h999
  • 395
  • 1
  • 5
  • 21
  • so what is the problem ? What are your seeing on screen which not as per your needs ? – CodenameLambda1 Aug 26 '13 at 04:40
  • 1
    I have drawn polygon and then trying to scale it,when i am scaling polygon,scaled polygon is drawing at different place.Not where i have drawn initial polygon. – h999 Aug 26 '13 at 05:00

1 Answers1

4

The problem is that you're used to UIView transformation, which is done from the center of the view.
CGPath transformation is done on the points (imagine CGPointZero as the center of the path).
My solution: translate to CGPointZero , scale , and then back to your original coordinates.

CGPathRef CGPath_NGCreateCopyByScalingPathAroundCentre(CGPathRef path,
                                           const float scale)
{
    CGRect bounding = CGPathGetPathBoundingBox(path);
    CGPoint pathCenterPoint = CGPointMake(CGRectGetMidX(bounding), CGRectGetMidY(bounding));

    CGAffineTransform translateAndScale = CGAffineTransformTranslate( CGAffineTransformMakeScale(scale, scale), - pathCenterPoint.x, -pathCenterPoint.y) ;
    CGAffineTransform translateBack = CGAffineTransformMakeTranslation(pathCenterPoint.x, pathCenterPoint.y);

    CGPathRef centeredAndScaled = CGPathCreateCopyByTransformingPath(path, &translateAndScale);
    CGPathRef translatedPathRef = CGPathCreateCopyByTransformingPath(centeredAndScaled, &translateBack);

    CGPathRelease(centeredAndScaled);

    return translatedPathRef;
}
Nir Golan
  • 1,336
  • 10
  • 24