Skip to content

Instantly share code, notes, and snippets.

@rizo
Last active December 11, 2015 11:08
Show Gist options
  • Save rizo/4591382 to your computer and use it in GitHub Desktop.
Save rizo/4591382 to your computer and use it in GitHub Desktop.
// Draws a test finite automata node with CoreGraphics functions.
- (void)drawRect:(NSRect)rect
{
// Obtain the current context.
CGContextRef context = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
// Set the color space.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextSetFillColorSpace(context, colorSpace);
CGContextSetStrokeColorSpace(context, colorSpace);
CGColorSpaceRelease(colorSpace);
// Fill the view backgroud.
CGFloat canvasBackgroundColor[] = {1.0f, 1.0f, 1.0f, 1.0f};
CGContextSetFillColor(context, canvasBackgroundColor);
CGContextFillRect(context, rect);
// Define the node geometry.
CGSize nodeSize = CGSizeMake(50.0f, 50.0f);
CGPoint nodeCenterPosition = CGPointMake(100.0f, 150.0f);
CGPoint nodePosition = CGPointMake(nodeCenterPosition.x - nodeSize.width / 2.0f,
nodeCenterPosition.y - nodeSize.height / 2.0f);
CGRect nodeRect = CGRectMake(nodePosition.x, nodePosition.y, nodeSize.width, nodeSize.height);
// Stroke the node path.
CGFloat nodeStrokeColor[] = {0.0f, 0.0f, 0.0f, 1.0f};
CGContextSetLineWidth(context, 3.0);
CGContextSetStrokeColor(context, nodeStrokeColor);
CGContextAddEllipseInRect(context, nodeRect);
CGContextStrokePath(context);
// Fill the node background.
CGFloat nodeBackgroundColor[] = {1.0f, 1.0f, 1.0f, 1.0f};
CGContextSetFillColor(context, nodeBackgroundColor);
CGContextFillEllipseInRect(context, nodeRect);
// Draw the node label.
NSString *nodeLabelText = @"s0";
NSFont *font = [NSFont fontWithName:@"Helvetica" size:24.0];
NSDictionary *textAttributes = @{NSFontAttributeName: font};
CGSize labelSize = [nodeLabelText sizeWithAttributes:textAttributes];
CGPoint labelPosition = CGPointMake(nodeCenterPosition.x - labelSize.width / 2.0f,
nodeCenterPosition.y - labelSize.height / 2.0f);
CGRect labelRect = CGRectMake(labelPosition.x, labelPosition.y, labelSize.width, labelSize.height);
[nodeLabelText drawInRect:labelRect withAttributes:textAttributes];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment