TweetFollow Us on Twitter

Paint Tools
Volume Number:5
Issue Number:6
Column Tag:Programmer's Workshop

Related Info: Quickdraw

Spray Can and Paint Bucket Tools

By Kevin Parichan, Reedley, CA

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

[Kevin Parichan is a senior, computer science major attending Cal Poly in San Luis Obispo. He has been programming on the Mac since early 1985 when he got his first computer, the 128K Mac. Right now he is doing some work using 4th Dimension.]

Painting Tools

When the Macintosh was first introduced, along with it came MacPaint and all those nifty painting tools that first awed us.

I’m the kind of person who likes to take things apart, see how they work, and see if I can figure them out. So it has been with MacPaint’s tools.

We can all certainly create cheap imitation tools that expand ovals and rectangles that flash every time we move them. And since there are other, and far superior, painting programs around these days, certainly other people have figured out the mysteries of MacPaint. But I wanted to figure them out for myself.

I thought what better way than to create a Pascal unit that can be used by anybody whose program’s purpose does not emphasize graphics, but would still like to supply the standard tools to their users.

Since completing this unit (right now only in a Turbo Pascal version, and available on GEnie) I thought that I might share some of my knowledge with the rest of the people out there who are still scratching their heads.

Of course, I won’t show you everything. That would be too easy. I’ll just show you how you can create both the Spray Can and Paint Bucket tools using some simple logic and those new Quickdraw routines that surfaced with the MacPlus.

Along the way I did get some help

Technical Note #163 gives a very short code fragment on how to do a color fill routine. The problem is that SeedCFill and SeedFill want different parameters. Plus, SeedCFill uses Color Quickdraw which of course doesn’t much help those of us who can’t afford a Mac II.

You may also notice the function, NewBitMap. I’ve been using this since I first saw it in Scott Boyd’s article on animated bitmaps. It’s a handy little function.

I’ve tried to set up the routines as independent from the program as possible and to do this I use the current grafport to pass information to the routines. For both tools we use the portBits, portRect, and pnPat fields.

SeedFill and CopyMask were added when the MacPlus was introduced. They are both described in Inside Mac Vol. IV. Both are routines that operate on a portion of a bitmap, but I’ll be using them on whole bitmaps which has yet to cause any problems. The spray can tool uses only CopyMask, so let’s start with that.

The Spray Can

{1}

PROCEDURE CopyMask (srcBits, maskBits, dstBits: BitMap; srcRect, maskRect, 
dstRect: Rect);

As Inside Mac states: “ . . . it transfers a bit image from the source bitmap to the destination bitmap only where the corresponding bit of the mask rectangle is a 1.” As you can see in the example below.

Figure 1

So for the spray can tool what we’re going to do is create a source bitmap that contains the pattern we want to spray with, and a mask bitmap which has 1’s corresponding to where we want to paint. In our case, a spray pattern.

In both examples, it’s the call to CopyMask which is used to apply a pattern.

First thing we need to do is get the information we need from the current grafport.

{2}

GetPort(workPort);
workBits:= workPort^.portBits;
workRect:= workPort^.portRect;
workPat:= workPort^.pnPat;

Then set up the mask bitmap representing an exact duplicate of the spray can cursor, and also the source bitmap which is filled with the pattern we want to spray with.

You may notice that the source bitmap is the same size as the area we are spraying into. That is because we want a continuous pattern throughout the window. If we used a smaller area, then the pattern from one spraying to the next would overlap and give us garbage on the screen. Also, the bounds for SprayBits is 17 pixels on edge, while a cursor is 16 pixels on edge. That has to do with the way QuickDraw defines rectangles. I don’t understand it fully, but I do know that changing the 16’s into 15’s bombs the program when you use the spray can.

As everybody does when they get a new piece of code: experiment with it.

{3}

GetIndString(theStr,128,1);
SetRect(tempRect,0,0,16,16);
if NewBitMap(SprayBits,tempRect) = nil then Exit;
StuffHex(SprayBits.baseAddr,theStr);
if NewBitMap(PatBits,workRect) = nil then begin
  DisposPtr(SprayBits.baseAddr);
  Exit;
end;
SetPortBits(PatBits);
FillRect(workRect,workPat);
SetPortBits(workBits);

Next is the main loop. The tickcount is used to slow down the motion so that too much isn’t sprayed at one time. Slowing down too much makes the spraying drag behind your mouse movements.

{4}

repeat
  GetMouse(where);
  with where do
    SetRect(tempRect,h-8,v-8,h+8,v+8);
  tickValue:= TickCount + 1;
  repeat until (tickValue <= TickCount);
  CopyMask(PatBits, SprayBits, workBits, tempRect, SprayBits.bounds, 
tempRect);
  tickValue:= TickCount;
  repeat until (tickValue <= TickCount);
until NOT Button;

That’s all there is to the spray can, so now onto the...

The Paint Bucket

For the paint bucket we also need to use SeedFill.

{5}

PROCEDURE SeedFill (srcPtr, desPtr: Ptr; srcRow, dstRow, height, words, 
seedH, seedV: Integer);

As Inside Mac state, “ . . . computes a destination bit image with 1’s only in the pixels where paint can leak from the starting seed point . . .” All we need to do then after calling SeedFill is apply a pattern to the destination bit image which can be accomplished with CopyMask

SeedFill uses pointers pointing into bitmaps. It’s easier just to copy the working image to a new bitmap and set the pointers to its baseAddr and it helps in other ways as explained below. Besides, windows usually only show a view of a much larger image. If SeedFill is to work on a whole image you would use the larger image’s baseAddr anyway. But if you really know what you’re doing and only want to fill a portion of the bitmap, then I’m afraid you’re going to have to do some pointer arithmetic.

Get the same information as before.

{6}

GetPort(workPort);
workBits:= workPort^.portBits;
workRect:= workPort^.portRect;
workPat:= workPort^.pnPat;

Set up our two bitmaps for the calls to SeedFill and CopyMask. Make a copy of the image we are using the paint bucket on, which gets our addresses right and also helps us because the current grafport is a window and its bitmap also contains the title bar. You can also see where this code needs modification. What about scroll bars and and the grow icon. A simple fix is to pass to the routines the area you want to fill or spray in. Don’t think clipping the area will work. SeedFill is not clipped to the current grafport. Take out the code that makes a copy of the work image and see for yourself.

{7}

if NewBitMap(dstMap,workRect) = nil then Exit;
if NewBitMap(srcMap,workRect) = nil then begin
  DisposPtr(dstMap.baseAddr);
  Exit;
end;
CopyBits(workBits,srcMap,workRect,workRect,srcCopy,nil);

Now we check to see if we are filling on a black pixel. To act just like a normal paint bucket we need to apply the pattern to the black areas instead of the white. But SeedFill only works on white, so we invert the image before and after calling SeedFill.

{8}

onBlack:= GetPixel(where.h,where.v);
if onBlack then begin
  SetPortBits(srcMap);
  InvertRect(workRect);
  SetPortBits(workBits);
end;

Set up the bitmap containing the pattern we want to fill with. Don’t forget to invert the pattern as well if we are starting the fill on a black pixel.

{9}

if NewBitMap(PatBits,workRect) = nil then begin
  DisposPtr(dstMap.baseAddr);
  DisposPtr(srcMap.baseAddr);
  Exit;
end;
SetPortBits(PatBits);
FillRect(workRect,workPat);
if onBlack then InvertRect(workRect);
SetPortBits(workBits);

This is the area that I don’t want to be bothered with. I just say that I’m attempting to fill the entire bitmap. Don’t forget to make words an even number. Height is the height of our image in pixels and words is the width of our image in words (as in 2 bytes).

{10}

srcPtr:= srcMap.baseAddr;
srcRow:= srcMap.rowBytes;
dstPtr:= dstMap.baseAddr;
dstRow:= dstMap.rowBytes;
height:= dstMap.bounds.bottom - dstMap.bounds.top;
words:= (dstRow + 1) DIV 2;

And here it is. The code that does all the real work. Simple, isn’t it. Where is the point where the mouse was clicked in the window in local coordinates.

{11}

SeedFill(srcPtr,dstPtr,srcRow,dstRow,height,words,where.h,where.v);
CopyMask(PatBits,dstMap,srcMap,workRect,workRect,srcMap.bounds);

We check to see if we started filling on a black pixel, and if so, invert our image once again, then copybit it to the grafport.

{12}

if onBlack then begin
  SetPortBits(srcMap);
  InvertRect(workRect);
  SetPortBits(workBits);
end;
CopyBits(srcMap,workBits,workRect,workRect,srcCopy,nil);

Well, that’s it. Not much to it. There are some obvious places to improve upon, but like I said, I tried to make the code as generic as possible. It’s your job to customize it to suit your needs.

Listing:  ToolDemo.pas

Program ToolDemo;
{$U-}
{$R ToolDemoRes}

Uses
  MemTypes,QuickDraw,OSIntf,ToolIntf;
  
Const
  AppleMenu     = 128;
  FileMenu      = 129;
  EditMenu      = 130;
  ToolMenu      = 131;
    SprayItem   = 1;
    BucketItem  = 2;
  PatternMenu   = 132;
    WhiteItem   = 1;
    LtGrayItem  = 2;
    GrayItem    = 3;
    DkGrayItem  = 4;
    BlackItem   = 5;
  
Var
  myMenus      : array [AppleMenu..PatternMenu] of MenuHandle;
  myWindow      : WindowPtr;
  Finished      : Boolean;
  GrowArea      : Rect;
  CurrentPat    : Integer;
  CurrentTool   : Integer;

{##################################################################}
Function NewBitMap (VAR theBitMap : BitMap; theRect : Rect) : Ptr;
Begin
  NewBitMap:= nil;
  with theBitMap,theRect do begin
    rowBytes:= ((right-left+15) DIV 16) *2;
    baseAddr:= NewPtr(rowBytes * (bottom-top));
    bounds:= theRect;
    if MemError = noErr then
      NewBitMap:= baseAddr;
  end;
End;

Procedure DoSprayCan (where : Point);
Var
  workPort  : GrafPtr;
  workBits  : BitMap;
  workRect  : Rect;
  workPat   : Pattern;
  theStr    : Str255;
  tempRect  : Rect;
  SprayBits : BitMap;
  PatBits   : BitMap;
  tickValue : LongInt;
Begin
  GetPort(workPort);
  workBits:= workPort^.portBits;
  workRect:= workPort^.portRect;
  workPat:= workPort^.pnPat;

  GetIndString(theStr,128,1);
  SetRect(tempRect,0,0,16,16);
  if NewBitMap(SprayBits,tempRect) = nil then Exit;
  StuffHex(SprayBits.baseAddr,theStr);

  if NewBitMap(PatBits,workRect) = nil then begin
    DisposPtr(SprayBits.baseAddr);
    Exit;
  end;
  SetPortBits(PatBits);
  FillRect(workRect,workPat);
  SetPortBits(workBits);

  repeat
    GetMouse(where);
    with where do
      SetRect(tempRect,h-8,v-8,h+8,v+8);
    tickValue:= TickCount + 1;
    repeat until (tickValue <= TickCount);
    CopyMask(PatBits,SprayBits,workBits,tempRect,SprayBits.bounds,tempRect);
    tickValue:= TickCount;
    repeat until (tickValue <= TickCount);
  until NOT Button;
  
  DisposPtr(PatBits.baseAddr);
  DisposPtr(SprayBits.baseAddr);
End;

Procedure DoPaintBucket (where : Point);
Var
  workPort  : GrafPtr;
  workBits  : BitMap;
  workRect  : Rect;
  workPat   : Pattern;
  PatBits   : BitMap;
  onBlack   : Boolean;
  srcMap    : BitMap;
  dstMap    : BitMap;
  srcPtr    : Ptr;
  dstPtr    : Ptr;
  srcRow    : Integer;
  dstRow    : Integer;
  height    : Integer;
  words     : Integer;
Begin
  GetPort(workPort);
  workBits:= workPort^.portBits;
  workRect:= workPort^.portRect;
  workPat:= workPort^.pnPat;
  
  if NewBitMap(dstMap,workRect) = nil then Exit;
  if NewBitMap(srcMap,workRect) = nil then begin
    DisposPtr(dstMap.baseAddr);
    Exit;
  end;

  CopyBits(workBits,srcMap,workRect,workRect,srcCopy,nil);

  onBlack:= GetPixel(where.h,where.v);
  if onBlack then begin
    SetPortBits(srcMap);
    InvertRect(workRect);
    SetPortBits(workBits);
  end;
  
  if NewBitMap(PatBits,workRect) = nil then begin
    DisposPtr(dstMap.baseAddr);
    DisposPtr(srcMap.baseAddr);
    Exit;
  end;
  SetPortBits(PatBits);
  FillRect(workRect,workPat);
  if onBlack then InvertRect(workRect);
  SetPortBits(workBits);
  srcPtr:= srcMap.baseAddr;
  srcRow:= srcMap.rowBytes;
  dstPtr:= dstMap.baseAddr;
  dstRow:= dstMap.rowBytes;
  height:= dstMap.bounds.bottom - dstMap.bounds.top;
  words:= (dstRow + 1) DIV 2;

  SeedFill(srcPtr,dstPtr,srcRow,dstRow,height,words,where.h,where.v);
  CopyMask(PatBits,dstMap,srcMap,workRect,workRect,srcMap.bounds);
  
  if onBlack then begin
    SetPortBits(srcMap);
    InvertRect(workRect);
    SetPortBits(workBits);
  end;
  CopyBits(srcMap,workBits,workRect,workRect,srcCopy,nil);

  DisposPtr(srcMap.baseAddr);
  DisposPtr(dstMap.baseAddr);
  DisposPtr(PatBits.baseAddr);
End;

{##################################################################}
Procedure ProcessMenu (codeWord : LongInt);
Var
  menuNum   : Integer;
  itemNum   : Integer;
  itemStr   : Str255;
  dummy     : Integer;
Begin
  if codeWord <> 0 then begin
    menuNum := HiWord(codeWord);
    itemNum := LoWord(codeWord);
    case menuNum of
      AppleMenu :
        begin
          GetItem(myMenus[AppleMenu],itemNum,itemStr);
          dummy:= OpenDeskAcc(itemStr);
        end;
      FileMenu : Finished:= TRUE;
      EditMenu : if NOT SystemEdit(itemNum - 1) then ;
      ToolMenu :
        begin
          CheckItem(myMenus[ToolMenu],CurrentTool,false);
          CurrentTool:= itemNum;
          CheckItem(myMenus[ToolMenu],CurrentTool,true);
        end;
      PatternMenu :
        begin
          CheckItem(myMenus[PatternMenu],CurrentPat,false);
          CurrentPat:= itemNum;
          CheckItem(myMenus[PatternMenu],CurrentPat,true);
          SetPort(myWindow);
          case CurrentPat of
            WhiteItem   : PenPat(white);
            LtGrayItem  : PenPat(ltGray);
            GrayItem    : PenPat(gray);
            DkGrayItem  : PenPat(dkGray);
            BlackItem   : PenPat(black);
          end
        end;
    end; {case}
    HiliteMenu(0);
  end; {big if}
End;

{##################################################################}
Procedure DealWithMouseDowns(theEvent: EventRecord);
Var
  whichWindow   : WindowPtr;
  mouseLoc      : Point;
  windowLoc     : Integer;
  position      : LongInt;
Begin
  mouseLoc:= theEvent.where;
  windowLoc:= FindWindow(mouseLoc,whichWindow);
  case windowLoc of
    inMenuBar   : ProcessMenu(MenuSelect(mouseLoc));
    inSysWindow : SystemClick(theEvent,whichWindow);
    inDrag      : DragWindow(whichWindow,mouseLoc,screenBits.bounds);
    inGoAway    : if TrackGoAway(whichWindow,mouseLoc) then Finished:= 
true;
    inGrow :
      begin
        position:= GrowWindow(whichWindow,mouseLoc,GrowArea);
        if position <> 0 then begin
          SizeWindow(whichWindow,loword(position),hiword(position),false);
          SetPort(whichWindow);
          InvalRect(whichWindow^.portRect);
        end;
      end;
    inZoomIn,inZoomOut :
      begin
        if TrackBox(whichWindow,mouseLoc,windowLoc) then begin
          SetPort(whichWindow);
          ClipRect(whichWindow^.portRect);
          EraseRect(whichWindow^.portRect);
          ZoomWindow(whichWindow,windowLoc,true);
          InvalRect(whichWindow^.portRect);
        end;
      end;
    inContent :
      begin
        if whichWindow <> FrontWindow then
          SelectWindow(whichWindow)
        else begin
          SetPort(whichWindow);
          GlobalToLocal(mouseLoc);
          case CurrentTool of
            SprayItem   : DoSprayCan(mouseLoc);
            BucketItem  : DoPaintBucket(mouseLoc);
          end;
        end;
      end;
  end;
End;

Procedure DealWithKeyDowns(theEvent: EventRecord);
Var
  CharCode  : char;
Begin
  CharCode:= CHR(BitAnd(theEvent.message,charCodeMask));
  if BitAnd(theEvent.modifiers,CmdKey) = CmdKey
    then ProcessMenu(MenuKey(CharCode));
End;

Procedure DealWithActivates(theEvent: EventRecord);
Var
  theWindow : WindowPtr;
Begin
  theWindow := WindowPtr(theEvent.message);
  if Odd(theEvent.modifiers)
    then SetPort(theWindow);
End;

Procedure DealWithUpdates(theEvent: EventRecord);
Var
  theWindow : WindowPtr;
  tempPort  : WindowPtr;
Begin
  theWindow := WindowPtr(theEvent.message);
  GetPort(tempPort);
  SetPort(theWindow); 
  BeginUpDate(theWindow);
    ClipRect(theWindow^.portRect);
    EraseRect(theWindow^.portRect);
    PenSize(5,5);
    FrameOval(theWindow^.portRect);
    PenSize(1,1);
  EndUpDate(theWindow);
  SetPort(tempPort);
End;

Procedure MainEventLoop;
Var
  Event : EventRecord;
Begin
  repeat
    SystemTask;
    if GetNextEvent(everyEvent, Event) then
      case Event.what of
        mouseDown   : DealWithMouseDowns(Event);
        AutoKey     : DealWithKeyDowns(Event);
        KeyDown     : DealWithKeyDowns(Event);
        ActivateEvt : DealWithActivates(Event);
        UpdateEvt   : DealWithUpdates(Event);
      end; {case}
  until Finished;
End;

{##################################################################}
Procedure SetupStuff;
Var
  index : Integer;
Begin
  MaxApplZone;
  InitGraf(@thePort);
  InitFonts;
  InitWindows;
  InitMenus;
  TEInit;
  InitDialogs(nil);

  for index:= AppleMenu to PatternMenu do begin
    myMenus[index] := GetMenu(index);
    InsertMenu(myMenus[index],0);
  end;
  AddResMenu(myMenus[AppleMenu],’DRVR’);
  DrawMenuBar;
  CurrentTool:= SprayItem;
  CurrentPat:= BlackItem;
  CheckItem(myMenus[ToolMenu],CurrentTool,true);
  CheckItem(myMenus[PatternMenu],CurrentPat,true);
  myWindow:= GetNewWindow(1000,nil,pointer(-1));
  
  Finished:= false;
  with screenBits.bounds do
    SetRect(GrowArea,150,150,right,bottom);

  FlushEvents(everyEvent,0);

  InitCursor;
End;

Begin
  SetupStuff;  
  MainEventLoop;
End.
Listing:  ToolDemo.r

ToolDemoRes

Type MENU
,128
\14

,129
File
Quit/Q

,130
Edit
Undo/Z
(-
Cut/X
Copy/C
Paste/V
Clear

,131
Tools
Spray Can
Paint Bucket

,132
Patterns
White/1
Light Gray/2
Gray/3
Dark Gray/4
Black/5

Type STR#
,128
1
0100001020800400002282001048010104409008022208004120000408000080

Type WIND
,1000
Tool Demo
50 50 300 400
Visible GoAway
8
0

 
AAPL
$570.56
Apple Inc.
+13.59
GOOG
$609.46
Google Inc.
+8.66
MSFT
$29.11
Microsoft Corpora
-0.65
MacNews Search:
Community Search:
view counter

view counter
view counter
view counter
view counter
view counter
view counter
view counter
view counter

Fruit Ninja Gets New Update With Powerup...
Fruit Ninja is about to get its biggest update yet to celebrate its second anniversary on Thursday, May 24th. The key new element in the game appears to be that players will now be able to earn an in-game currency, called starfruit, that can be used to buy new powerups from new characters Gutsu and Truffles, introduced in the new trailer produced... | Read more »
Fotor – CameraBag Review
Fotor – CameraBag Review By Jennifer Allen on May 23rd, 2012 Our Rating: :: PLENTIFULiPhone App - Designed for the iPhone, compatible with the iPad A photography app that wants to be able to do everything that could ever be asked of it.   | Read more »
playGO AP1 is the Next Generation of Aud...
With all of Apple’s relatively recent success in the smartphone and tablet market, we can forget sometimes that what kicked off their modern dominance was a device that simply played music. BICOM, Inc. has been recognizing how important music is to the company with their playGo series of iOS receiver systems. The newest model, the playGo AP1, is... | Read more »
Monkey Pong Review
Monkey Pong Review By Angela LaFollette on May 23rd, 2012 Our Rating: :: BALL BUSTING ACTIONiPhone App - Designed for the iPhone, compatible with the iPad Help the hungry monkey reach all the fruit by bouncing a ball in this family-friendly arcade game.   | Read more »
Heroes & Generals Enters Closed Beta
Creators of Hitman, Roto-Moto, has launched a closed beta of their game, Heroes & Generals. The game is a massively multiplayer first-person shooter involving online fighting between the Axis and Allied forces in Europe. | Read more »
FeedFriendly Review
FeedFriendly Review By Angela LaFollette on May 23rd, 2012 Our Rating: :: EASY TO USEUniversal App - Designed for iPhone and iPad Combine the top three social network newsfeed updates into one location with the help of FeedFriendly.   | Read more »
Favorite 4: Euro 2012 Apps
In a matter of weeks, one of the biggest soccer tournaments out there begins: Euro 2012. Qualification is over and 16 European teams are all lined up to prove which one is the best of the bunch. As a Brit, I’m ever hopeful that England will achieve glory but regardless of what happens, I’ll be enjoying seeing some high quality action. In honor of... | Read more »
Zombie Farm 2 Review
Zombie Farm 2 Review By Rob LeFebvre on May 23rd, 2012 Our Rating: Universal App - Designed for iPhone and iPad Take on the role of a social game farmer who plants both crops AND zombies in this sequel to the original hit, Zombie Farm.   Developer: The Playforge | Read more »
Facebook Pages Manager Does Exactly What...
Sick of hearing about the Facebook IPO? Want to hear about something actually related to the Facebook product? Well, I have good news then. Facebook has launched a new app that will come in handy for users who manage Facebook Pages. | Read more »
Score! Classic Goals Review
Score! Classic Goals Review By Jennifer Allen on May 23rd, 2012 Our Rating: :: GOAL!Universal App - Designed for iPhone and iPad Relive some classic goals by creating them in this addictive soccer game.   | Read more »
All contents are Copyright 1984-2010 by Xplain Corporation. All rights reserved. Theme designed by Icreon.