Create a colored bubble/circle programmatically in ObjectiveC and Cocoa

kdbdallas picture kdbdallas · Dec 10, 2008 · Viewed 37.8k times · Source

Can anyone guide me in the correct way to build a colored bubble/circle programmatically?

I can't use images as I need it to be able to be any color depending on user interaction.

My thought was maybe to make a white circle image and then overlay a color on top of it. However I am not sure if this would work, or how to really go about it.

If someone could point me the right direction I would appreciate it.

Answer

joshperry picture joshperry · Dec 10, 2008

There are a couple steps to drawing something in Cocoa.

First you need a path that will be used to define the object that you are going to be drawing. Take a look here Drawing Fundamental Shapes for a guide on creating paths in Cocoa. You will be most interested in sending the "appendBezierPathWithOvalInRect" message to an "NSBezierPath" object, this takes a rectangle that bounds the circle you want to draw.

This code will create a 10x10 circle at coordinates 10,10:

NSRect rect = NSMakeRect(10, 10, 10, 10);
NSBezierPath* circlePath = [NSBezierPath bezierPath];
[circlePath appendBezierPathWithOvalInRect: rect];

Once you have your path you want to set the color for the current drawing context. There are two colors, stroke and fill; stroke is the outline of the path and the fill is the interior color. To set a color you send "set" to an "NSColor" object.

This sets the stroke to black and the fill to red:

[[NSColor blackColor] setStroke];
[[NSColor redColor] setFill];

Now that you have your path and you have your colors set just fill the path and then draw it:

[path stroke];
[path fill];

All of this will need to be done in a graphics context like in drawRect of a view perhaps. All of this together with a graphics context would look like this:

- (void)drawRect:(NSRect)rect
{
    // Get the graphics context that we are currently executing under
    NSGraphicsContext* gc = [NSGraphicsContext currentContext];

    // Save the current graphics context settings
    [gc saveGraphicsState];

    // Set the color in the current graphics context for future draw operations
    [[NSColor blackColor] setStroke];
    [[NSColor redColor] setFill];

    // Create our circle path
    NSRect rect = NSMakeRect(10, 10, 10, 10);
    NSBezierPath* circlePath = [NSBezierPath bezierPath];
    [circlePath appendBezierPathWithOvalInRect: rect];

    // Outline and fill the path
    [circlePath stroke];
    [circlePath fill];

    // Restore the context to what it was before we messed with it
    [gc restoreGraphicsState];
}