ページ

2008年4月18日金曜日

RubberBand(その3)Sketchのソースを読む (2)

このエントリーをブックマークに追加 このエントリーを含むはてなブックマーク

前回はイベントハンドリングの部分を読んだので、今回は描画コードを読み解く。

SKTGraphicView.m

- (void)drawRect:(NSRect)rect {
for (NSInteger index = graphicCount - 1; index>=0; index--) {
(1) SKTGraphic *graphic = [graphics objectAtIndex:index];
(2) [graphic drawContentsInView:self isBeingCreateOrEdited:(graphic==_creatingGraphic || graphic==_editingGraphic)];
if (drawSelectionHandles) {
(3)[graphic drawHandlesInView:self];
}
}
}

リストから図形をひとつずつ取り出して(1)、描画していく(2)。ハンドルがある場合はこれも描く(3)。

(3)の drawHandlesInView: を見てみよう。

SKTGraphic.m

- (void)drawHandlesInView:(NSView *)view {

// Draw handles at the corners and on the sides.
NSRect bounds = [self bounds];
[self drawHandleInView:view atPoint:NSMakePoint(NSMinX(bounds), NSMinY(bounds))];
[self drawHandleInView:view atPoint:NSMakePoint(NSMidX(bounds), NSMinY(bounds))];
[self drawHandleInView:view atPoint:NSMakePoint(NSMaxX(bounds), NSMinY(bounds))];
[self drawHandleInView:view atPoint:NSMakePoint(NSMinX(bounds), NSMidY(bounds))];
[self drawHandleInView:view atPoint:NSMakePoint(NSMaxX(bounds), NSMidY(bounds))];
[self drawHandleInView:view atPoint:NSMakePoint(NSMinX(bounds), NSMaxY(bounds))];
[self drawHandleInView:view atPoint:NSMakePoint(NSMidX(bounds), NSMaxY(bounds))];
[self drawHandleInView:view atPoint:NSMakePoint(NSMaxX(bounds), NSMaxY(bounds))];

}

単純に8つのハンドルを drawHandleInView:atPoint: を使って描画している。描画メソッドは次の通り。

- (void)drawHandleInView:(NSView *)view atPoint:(NSPoint)point {

// Figure out a rectangle that's centered on the point but lined up with device pixels.
NSRect handleBounds;
handleBounds.origin.x = point.x - SKTGraphicHandleHalfWidth;
handleBounds.origin.y = point.y - SKTGraphicHandleHalfWidth;
handleBounds.size.width = SKTGraphicHandleWidth;
handleBounds.size.height = SKTGraphicHandleWidth;
handleBounds = [view centerScanRect:handleBounds];

// Draw the shadow of the handle.
NSRect handleShadowBounds = NSOffsetRect(handleBounds, 1.0f, 1.0f);
[[NSColor controlDarkShadowColor] set];
NSRectFill(handleShadowBounds);

// Draw the handle itself.
[[NSColor knobColor] set];
NSRectFill(handleBounds);

}

影と本体を NSRectFill()で描画している。これだけ。
するとこんなのが表示される。


- - - - -
Sketchにおけるラバーバンド(ハンドル)の実装方法がわかった。こうして見ると特別複雑なことはやっていない(グリッドやルーラーが入ると若干わかりづらいところもあるが)。これを参考に今度は自前のラバーバンドを作ってみよう。