• MacTech Network:
  • Tech Support
  • |
  • MacForge.net
  • |
  • Apple News
  • |
  • Register Domains
  • |
  • SSL Certificates
  • |
  • iPod Deals
  • |
  • Mac Deals
  • |
  • Mac Book Shelf

MAC TECH

  • Home
  • Magazine
    • About MacTech in Print
    • Issue Table of Contents
    • Subscribe
    • Risk Free Sample
    • Back Issues
    • MacTech DVD
  • Archives
    • MacTech Print Archives
    • MacMod
    • MacTutor
    • FrameWorks
    • develop
  • Forums
  • News
    • MacTech News
    • MacTech Blog
    • MacTech Reviews and KoolTools
    • Whitepapers, Screencasts, Videos and Books
    • News Scanner
    • Rumors Scanner
    • Documentation Scanner
    • Submit News or PR
    • MacTech News List
  • Store
  • Apple Expo
    • by Category
    • by Company
    • by Product
  • Job Board
  • Editorial
    • Submit News or PR
    • Writer's Kit
    • Editorial Staff
    • Editorial Calendar
  • Advertising
    • Benefits of MacTech
    • Mechanicals and Submission
    • Dates and Deadlines
    • Submit Apple Expo Entry
  • User
    • Register for Ongoing Raffles
    • Register new user
    • Edit User Settings
    • Logout
  • Contact
    • Customer Service
    • Webmaster Feedback
    • Submit News or PR
    • Suggest an article
  • Connect Tools
    • MacTech Live Podcast
    • RSS Feeds
    • Twitter

ADVERTISEMENT
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

 
MacTech Only Search:
Community Search:

 
 
 

 
 
 
 
 
  • SPREAD THE WORD:
  • Slashdot
  • Digg
  • Del.icio.us
  • Reddit
  • Newsvine
  • Generate a short URL for this page:



MacTech Magazine. www.mactech.com
Toll Free 877-MACTECH, Outside US/Canada: 805-494-9797
MacTech is a registered trademark of Xplain Corporation. Xplain, "The journal of Apple technology", Apple Expo, Explain It, MacDev, MacDev-1, THINK Reference, NetProfessional, Apple Expo, MacTech Central, MacTech Domains, MacNews, MacForge, and the MacTutorMan are trademarks or service marks of Xplain Corporation. Sprocket is a registered trademark of eSprocket Corporation. Other trademarks and copyrights appearing in this printing or software remain the property of their respective holders.
All contents are Copyright 1984-2010 by Xplain Corporation. All rights reserved. Theme designed by Icreon.
 
Nov. 20: Take Control of Syncing Data in Sow Leopard' released
Nov. 19: Cocktail 4.5 (Leopard Edition) released
Nov. 19: macProVideo offers new Cubase tutorials
Nov. 18: S Stardom anounces Safe Capsule, a companion piece for Apple's
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live