2

我正在尝试绘制源自一个点(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。我究竟做错了什么 ?

4

1 回答 1

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

结果:

在此处输入图像描述

于 2013-02-22T19:06:39.970 回答