[iOS]座標と描画 | Cocoa練習帳

[iOS]座標と描画

Mac OS Xでは、基本的に描画の座標は左下が原点だ。


iOSでは、UIKitとCoreAnimationでは左上が原点(便宜上、ULO(upper-left-origin)と呼ぶ)、Core Graphicsでは左下が原点(便宜上、LLO(lower-left-origin)と呼ぶ)だそうだ。試してみよう。




まず、Mac OS Xから。NSViewのサブクラスを作成して、以下の描画コードを追加する。




- (void)drawRect:(NSRect)dirtyRect
{
    /* LLO(lower-left-origin) */
    NSGraphicsContext   *nsctx = [NSGraphicsContext currentContext];
    CGContextRef    context = (CGContextRef)[nsctx graphicsPort];
    CGContextSetLineWidth(context, 4.0);
    CGContextBeginPath(context);
    CGContextMoveToPoint(context, 10.0, 30.0);
    CGContextAddLineToPoint(context, 10.0, 10.0);
    CGContextDrawPath(context, kCGPathStroke);
    CGContextMoveToPoint(context, 10.0, 10.0);
    CGContextAddLineToPoint(context, 30.0, 10.0);
    CGContextDrawPath(context, kCGPathStroke);
}



実行。確かに左下が原点だ。







次にiPhoneで確認。画像を座標 (10.0, 10.0) に描画する。




- (void)drawRect:(CGRect)rect
{
    /* ULO(upper-left-origin) */
    [self.upperLeftOriginImage drawAtPoint:CGPointMake(10.0, 10.0)];
}



実行。向きも変えてみる。確かに左上に描画される。




ULO縦

ULO横




今度はパスを座標 (10.0, 10.0) に描画するコードを追加。




- (void)drawRect:(CGRect)rect
{
    /* ULO(upper-left-origin) */
    [self.upperLeftOriginImage drawAtPoint:CGPointMake(10.0, 10.0)];
 
    /* LLO(lower-left-origin) */
    CGContextRef    context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 4.0);
    CGContextBeginPath(context);
    CGContextMoveToPoint(context, 10.0, 30.0);
    CGContextAddLineToPoint(context, 10.0, 10.0);
    CGContextDrawPath(context, kCGPathStroke);
    CGContextMoveToPoint(context, 10.0, 10.0);
    CGContextAddLineToPoint(context, 30.0, 10.0);
    CGContextDrawPath(context, kCGPathStroke);
}



実行。赤丸の箇所に描画。あれ?左上に描画されている。




LLO縦

LLO横




何かを勘違いしているのだろうか?




ソースコード
GitHubからどうぞ。

https://github.com/murakami/workbook/tree/master/ios/Coordinate - GitHub


関連情報
Drawing and Printing Guide for iOS

「Default Coordinate Systems and Drawing in iOS」の章を参照。