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

回転した 2 本の線も、何らかの形でずれているように見えます。レイヤーのアンカーポイントはデフォルトで 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 に答える