wjb
wjb

Reputation: 21

UIBezierPath lines with same origin

I'm trying to draw lines originating from one point (the center of the UIView) like so:

- (void)drawRect:(CGRect)rect {
   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(self.bounds.size.width/2.0f, self.bounds.size.height/2.0f);
    CGPoint end = CGPointMake(start.x + start.x/2, start.y);
    [path moveToPoint:start];
    [path addLineToPoint:end];
    return path;
}

The idea is to draw the same line and apply a rotation (around the center = the start of the line). The result is this:

https://dl.dropbox.com/u/103998739/bezierpath.png

The two rotated lines appear to be also offset in some way. The layer anchorpoint is default 0.5/0.5. What am I doing wrong ?

Upvotes: 2

Views: 1428

Answers (1)

Martin R
Martin R

Reputation: 539685

In iOS, the default coordinate system origin is in the top-left corner of the layer. (The anchorpoint is relevant for the relation between the layer and its superlayer, but not for the coordinate system within the layer.)

To move the origin of the coordinate system to the center of the layer, you can apply a translation first:

- (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;
}

Result:

enter image description here

Upvotes: 1

Related Questions