Wednesday, June 5, 2013

UIBezierPath applyTransform example in Objective C (iOS).


UIBezierPath applyTransform

Transforms all points in the path using the specified affine transform matrix.

- (void)applyTransform:(CGAffineTransform)transform

Parameters
transform
The transform matrix to apply to the path.

Discussion of [UIBezierPath applyTransform]
This method applies the specified transform to the path’s points immediately. The modifications made to the path object are permanent. If you do not want to permanently modify a path object, you should consider applying the transform to a copy.

UIBezierPath applyTransform example.
- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, self.bounds.size.width/2.0f, self.bounds.size.height/2.0f);

    UIBezierPath *path = [self createPath];
    [path stroke];

    path = [self createPath];
    CGAffineTransform rot = CGAffineTransformMakeRotation(2 * M_PI/16);
    [path applyTransform:rot];
    [path stroke];

    path = [self createPath];
    rot = CGAffineTransformMakeRotation( 2 * M_PI/8);
    [path applyTransform:rot];
    [path stroke];
}

- (UIBezierPath *) createPath {
    UIBezierPath *path = [UIBezierPath bezierPath];
    CGPoint start = CGPointMake(0, 0);
    CGPoint end = CGPointMake(self.bounds.size.width/4.0f, 0);
    [path moveToPoint:start];
    [path addLineToPoint:end];
    return path;
}

Example of [UIBezierPath applyTransform].
CGAffineTransform translate = CGAffineTransformMakeTranslation(-1 * (box.origin.x + (box.size.width / 2)), -1 * (box.origin.y + (box.size.height / 2)));
[path applyTransform:translate];

CGAffineTransform rotate = CGAffineTransformMakeRotation(DegreesToRadians(90));
[path applyTransform:rotate];

translate = CGAffineTransformMakeTranslation((box.origin.x + (box.size.width / 2)), (box.origin.y + (box.size.height / 2)));
[path applyTransform:translate];

UIBezierPath applyTransform example.
- (void) scaleAllPaths: (CGFloat) scaleFactor
{
  CGAffineTransform transform = CGAffineTransformMakeScale(scaleFactor,scaleFactor);
  for (UIBezierPath *bezierPath in availablePaths){
    [bezierPath applyTransform:transform];
  }
}

- (void)drawRect:(CGRect)rect
{
  ...
  for (int i = 0; i < currentPathIndex; i++) {
    UIBezierPath *bezierPath = [availablePaths objectAtIndex:i];
    CGPathRef path = bezierPath.CGPath;
    CGContextBeginPath(context);
    CGContextAddPath(context, path);
    CGContextDrawPath(context, kCGPathEOFill);
  }
  ...
}

End of UIBezierPath applyTransform example article.