1

I am making a drawing app for iOS and I have the following classes:

  • CanvasViewController holds a CanvasView and allows you to select a Brush for use in drawing
  • CanvasView is a UIView that contains a background color and an array of Stroke that are rendered by wiring up touches events and drawRect
  • Stroke is an NSObject that contains a UIBezierPath *path and a Brush
  • Brush contains an int brushType that is defined by a typedef and can be things like BrushTypeSolid, BrushTypeSpray, BrushTypePattern

Initially I thought about how I would handle drawing different brushType in my drawRect and it would be something like the following:

in drawrect

CGContextRef context = UIGraphicsGetCurrentContext();

UIGraphicsBeginImageContext(self.frame.size);

if ([squigglesArray count] > 0)  {

    for (WDSquiggle *squiggle in squigglesArray) {
        [self drawSquiggle:squiggle inContext:context];
    }
}

[self drawSquiggle:currentSquiggle inContext:context];

UIGraphicsEndImageContext();

in drawSquiggle

switch (squiggle.brushType): {
    case BrushTypeSolid:
         //solid brush stuff
         break;
    case BrushTypeX:
         //x stuff
         break;
}

However, now the drawing logic is all handled in a way that strongly ties the CanvasView and the BrushType together.

Is there an elegant way to encapsulate drawing logic in the BrushType or the Squiggle so that I could do something like:

[squiggle drawInRect:myRect]

or

[squiggle drawInView:myView]

Or, is this a stupid goal to have / I do not understand encapsulation?

tacos_tacos_tacos
  • 10,277
  • 11
  • 73
  • 126

1 Answers1

1

You could turn BrushType into a class with subclasses for each specific implementation and move the related logic inside drawSquiggle to it. drawSquiggle will simply call:

[squiggle.brushType draw......]

(you can certainly find the best name and parameters for this method)

This is a refactoring called "replace conditional with polymorphism".

Jordão
  • 55,340
  • 13
  • 112
  • 144
  • Is it advisable to have the drawing logic, ie `[squiggle drawInRect:myRect]` pushed to the `Squiggle`? or actually, `[squiggle drawInContext:(CGContextRef)context]` – tacos_tacos_tacos Apr 02 '12 at 04:09