トップ «前の日記(2012-02-14) 最新 次の日記(2012-02-16)» 編集

Cocoa練習帳

iOS/iPhone/iPad/watchOS/tvOS/MacOSX/Android プログラミング, Objective-C, Cocoa, Swiftなど

2012|01|02|03|04|05|06|07|08|09|10|11|12|
2013|01|02|03|04|05|06|07|08|09|10|11|12|
2014|01|02|03|04|05|06|07|08|09|10|11|12|
2015|01|02|03|04|05|06|07|08|09|10|11|12|
2016|01|02|03|04|05|06|07|08|09|10|11|12|
2017|01|02|03|04|05|06|07|08|09|10|11|12|
2018|01|02|03|04|05|06|07|08|09|10|11|12|
2019|01|02|03|04|05|06|07|08|09|10|11|12|
2020|01|02|03|04|05|06|07|08|09|10|11|12|
2021|01|02|03|04|05|06|07|08|09|10|11|12|
2022|01|02|03|04|05|06|07|08|09|10|11|12|
2023|01|02|03|04|05|06|07|08|09|10|11|12|
2024|01|02|03|

2012-02-15 [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);
}

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

Mac OS X

次に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横

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

_ 関連情報

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

トップ «前の日記(2012-02-14) 最新 次の日記(2012-02-16)» 編集