具有相同原点的UIBezierPath行

时间:2013-02-18 21:40:58

标签: objective-c uibezierpath

我正在尝试从一个点(UIView的中心)绘制线条,如下所示:

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

想法是绘制相同的线并应用旋转(围绕中心=线的起点)。结果如下:

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

两条旋转的线条似乎也以某种方式偏移。图层锚点默认为0.5 / 0.5。 我做错了什么?

1 个答案:

答案 0 :(得分:1)

在iOS中,默认坐标系原点位于图层的左上角。 (anchorpoint与图层及其超层之间的关系有关,但与图层内的坐标系无关。)

要将坐标系的原点移动到图层的中心,您可以先应用翻译:

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

结果:

enter image description here