2009年
12月 18
CGContextAddLines を使えば配列に入った CGPoint を結ぶ複数の線を描画することができます。例えばタッチの軌跡を描く場合などに使えます。しかし CGPoint はオブジェクトではないのでそのままでは NSMutableArray に入れることはできません。CGPoint の配列を使うにも最初に配列数を決めて定義しないといけないので、タッチの軌跡を描くような、描画点がいくつになるか分からないときには使うことが出来ません。
そこで、NSMutableArray に CGPoint を入れる方法です。ラッパクラスの NSValue を使います。このクラスは NSPoint, NSRect, NSSize, NSRange, CGPoint, CGRect, CGSize, CGAffineTransform などをラップできます。
使い方は以下の通りです。
// 配列に CGPoint を追加する NSMutableArray *points = [[NSMutableArray alloc] init]; CGPoint point = CGPointMake(0,0); [points addObject:[NSValue valueWithCGPoint:point]]; // 配列から CGPoint を取り出す NSValue* value = [points objectAtIndex:0]; CGPoint point2 = [value CGPointValue];
タッチイベントなどでタッチされた場所を CGPoint として取得して配列に追加
NSMutableArray *touchPoints = [[NSMutableArray alloc] init]; UITouch *touch = [touches anyObject]; CGPoint point = [touch locationInView:self.view]; [touchPoints addObject:[NSValue valueWithCGPoint:point]];
NSMutableArray からCGPoint の配列を作成して、CGContextAddLines で描画
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 5.0f);
CGContextSetRGBStrokeColor(context, 255, 0, 0, 50);
CGPoint points[touchPoints.count];
int i=0;
for (NSValue* value in touchPoints) {
points[i++] = [value CGPointValue];
}
CGContextAddLines(context, points, touchPoints.count);
CGContextStrokePath(context);
関連する投稿
2 Responses to “[iPhone] CGPoint を NSMutableArray に入れて CGContextAddLines で描画する”
Leave a Reply
Additional comments powered by BackType



5月 23rd, 2010 at 12:41 pm
[B!] 非オブジェクトの配列 http://www.syuhari.jp/blog/archives/1954 [iPhone] CGPoint を NSMutableArray に入れて CGContextAddLines で描画する | Sun Limited Mt.
This comment was originally posted on Twitter
5月 29th, 2010 at 10:46 am
http://tinyurl.com/34d79xk
[iPhone] CGPoint を NSMutableArray に入れて CGContextAddLines で描画する | Sun Limited Mt.
This comment was originally posted on Twitter