[Drawkit] Programmatically adding shapes
Graham Cox
graham.cox at bigpond.com
Fri May 16 21:41:11 PDT 2008
On 17 May 2008, at 9:19 am, Brad Larson wrote:
> DKDrawableShape *currentShape = [[DKDrawableShape alloc] init];
>
> // Make this shape a rectangle starting at (0,0) and ending at (50,50)
> [shape setPath:[DKShapeFactory rect]];
> [shape moveToPoint:NSMakePoint(0.0, 0.0)];
> [shape setSize:NSMakeSize(50.0, 50.0)];
>
> I don't know how to proceed. Do I add the shape to the active
> layer? If so, how? I might also need to set a style in there,
> somewhere, for the shape. Should I be doing this through a
> DKDrawingTool instead?
>
> I can probably figure this out if I spend some more time reading
> through the code, but I wanted to see if there might be an easier
> explanation for the process.
This is more or less OK (see, who needs documentation? ;-). One thing
to mention is that shapes initially take their location as being
centred, not at the top, left corner, so you want to
moveToPoint:NSMakePoint( 25, 25 ). If that's a problem for working
from SVG, there is a way to use the top, left point as the location by
using -setOffset(-0.5, -0.5). I can go into more detail on this if you
need it.
A possibly easier alternative to the above is to use [[DKDrawableShape
alloc] initWithRect:NSMakeRect(0,0,50,50)]; which sets the size, path
and location from the initial rect.
You don't need to set a style - the default style is set for you by
the init method of DKDrawableObject. This gives you *something* that
will work, though you'll be wanting to change this when you get
further along with extracting the "style" from SVG shapes.
To add the shape to the layer, first get the layer you want. This
doesn't need to be the active layer for programatically adding shapes,
but it does need to be a DKObjectDrawingLayer instance. You can use
the methods that DKDrawing inherits from DKLayerGroup to get any layer
(including searching down for a specific class of layer). You can use
the active layer if that makes sense, but do check its class first.
(Or you could create a layer, add objects to it, then add it to the
drawing, if that was a better approach - there's no reason you'd have
to add the layer first).
Assuming you have a layer of the right kind, to add the object, use:
[theLayer addObject:myShape];
There are other ways but this is the basic method, which adds the
object on top (in front) of any others. Take a look at
DKObjectOwnerLayer for more.
To also add the object to the selection, you can use:
[theLayer addObjectToSelection:myShape];
or
[theLayer replaceSelectionWithObject:myShape];
These methods are defined by DKObjectDrawingLayer.
Adding or selecting objects will cause them to get redrawn as
necessary, you don't need to do anything else to have them show up.
More information about the Drawkit
mailing list