TweetFollow Us on Twitter

Apr 99 Tips

Volume Number: 15 (1999)
Issue Number: 4
Column Tag: Tips & Tidbits

Apr 99 Tips

by Jeff Clites <online@mactech.com>

PixMap Rotation

CopyBits is one of the most powerful and ubiquitous of the Mac OS toolbox calls. It can scale, convert colors, and mask in a variety of ways. About the only thing it can't do is rotate an image. Similarly, we all know how to use DrawString to put text on the screen - but when we need to draw rotated text (say, for labeling a graph), we find no toolbox call up to the task. The routines below serve both needs.

RotatePixMap takes pointers to two PixMaps, and rotates the first into the second, rotating through a specified number of degrees (counter-clockwise). DrawRotatedString uses RotatePixMap to draw a string rotated to any angle, and then moves the graphics cursor accordingly. It also illustrates how to create a pair of pixel maps, draw into one, rotate into the other, and copy to the screen; a similar technique was used to rotate Clarus the dogcow in the figure below.

The code here only rotates pixel maps with 8-bit color depth or higher; it will return -1 if given a 1-bit image. It uses GWorlds, so requires at least System 7, but will work on both 68k and PowerPC machines. These functions form a valuable addition to the standard toolbox.

#include <Errors.h>
#include <fp.h>
#include "Rotate.h"

static void GetTrigs(float degrees, double_t *sinang, 
   double_t *cosang)
{
   // compute sine and cosine of the angle given in degrees;
   // check for special cases to avoid any rounding error
   if (degrees == 0) {
      *sinang = 0; *cosang = 1;
   } else if (degrees == 90 || degrees == -270) {
      *sinang = -1; *cosang = 0;
   } else if (degrees == 180 || degrees == -180) {
      *sinang = 0; *cosang = -1;
   } else if (degrees == 270 || degrees == -90) {
      *sinang = 1; *cosang = 0;
   } else {
      double_t radians = -degrees * pi / 180.0;
      *cosang = cos(radians);
      *sinang = sin(radians);
   }
}

OSErr RotatePixMap(PixMapPtr srcPm,
                                  PixMapPtr destPm,
   float degrees)
{
   double_t          cosang, sinang;
   short                x,y,x2,y2,i;
   char                *srcbyte, *destbyte;
   short                pixsize = srcPm->pixelSize / 8;
   unsigned char    blankByte = pixsize == 1 ? 0 : 255;

   short srcRowBytes = srcPm->rowBytes & 0x7FFF;
   short destRowBytes = destPm->rowBytes
                                           & 0x7FFF;

   short srcwidth = srcPm->bounds.right
                                           - srcPm->bounds.left,
      destwidth = destPm->bounds.right
                                           - destPm->bounds.left,
      srcheight = srcPm->bounds.bottom
                                           - srcPm->bounds.top,
      destheight = destPm->bounds.bottom
                                           - destPm->bounds.top;

   short srcCx = srcwidth/2,
                                           srcCy = srcheight/2;
   short destCx = destwidth/2,
                                           destCy = destheight/2;

   if (destPm->pixelSize/8
                                  != pixsize || pixsize < 1)
      return -1;   // requires 8 bit pixmap or higher
   
   GetTrigs(degrees, &sinang, &cosang);
   
   // loop over each element in dest, copying from source or          // setting to white
   for (y=0; y<destheight; y++) {
      destbyte = destPm->baseAddr +       y*destRowBytes;
      for (x=0; x<destwidth; x++) {
         x2 = srcCx + cosang*(x-destCx) +    sinang*(y-destCy);
         y2 = srcCy + cosang*(y-destCy) -    sinang*(x-destCx);
         if (x2 >= 0 && x2 < srcwidth
          && y2 >= 0 && y2 < srcheight) {
            srcbyte = srcPm->baseAddr +   y2*srcRowBytes
                  + x2*pixsize;
            for (i=0; i<pixsize; i++) {
               *destbyte++ = *srcbyte++;   // copy color
            }
         } else {
            for (i=0; i<pixsize; i++) {
               *destbyte++ = blankByte;   // fill in blank
            }
         }
      }
   }

   return noErr;
}


OSErr DrawRotatedString(Str255 s, float degrees)
{
   FontInfo   fi;
   short            cheight, cwidth, bufsize;
   Rect               srcR, destR, screenR;
   GWorldPtr      srcGW, destGW;
   PixMapHandle   srcPmH, destPmH;
   PixMapPtr      srcPm, destPm;
   CGrafPtr         origPort;
   GDHandle         origDevice;
   OSErr            err=noErr;
   double_t         cosang, sinang;

   // find the string size
   GetFontInfo( &fi );
   cheight = fi.ascent + fi.descent +   fi.leading;
   cwidth = StringWidth(s);
   
   // set buffer size (allow room for rotation)
   bufsize = (cheight > cwidth ?
                                        cheight*2 : cwidth*2);
   
   // create an offscreen GWorld in which to draw the string,
   // and another in which to draw the rotated version
   SetRect( &srcR, 0, 0, bufsize, cheight*2 );
   err = NewGWorld( &srcGW, 0, &srcR,
                                        NULL, NULL, 0 );
   if (err) return err;

   SetRect( &destR, 0, 0, bufsize, bufsize );
   err = NewGWorld( &destGW, 0, &destR,
                                        NULL, NULL, 0 );
   if (err) { DisposeGWorld( srcGW ); return err; }

   srcPmH = GetGWorldPixMap( srcGW );
   LockPixels( srcPmH );
   srcPm = *srcPmH;

   destPmH = GetGWorldPixMap( destGW );
   LockPixels( destPmH );
   destPm = *destPmH;

   // store original port, and draw string to source GWorld
   GetGWorld( &origPort, &origDevice );

   SetGWorld( srcGW, NULL );
   TextFont( origPort->txFont );
   TextSize( origPort->txSize );
   TextFace( origPort->txFace );
   EraseRect( &srcR );
   MoveTo( bufsize/2, cheight );
   DrawString( s );

   // rotate into the dest buffer
   RotatePixMap( srcPm, destPm, degrees );

   // copy to screen in OR mode, to avoid clobbering background
   SetGWorld( origPort, origDevice );
   SetRect( &screenR, 0, 0, bufsize, bufsize );
   OffsetRect( &screenR, 
                           origPort->pnLoc.h - bufsize/2,
         origPort->pnLoc.v - bufsize/2 );
   CopyBits((BitMap*)destPm,
                        (BitMap*)(*origPort->portPixMap),
         &destR, &screenR, srcOr, NULL );
   
   // release memory
   UnlockPixels( srcPmH );
   DisposeGWorld( srcGW );
   
   UnlockPixels( destPmH );
   DisposeGWorld( destGW );
   
   // finally, move the pen by the proper amount and direction
   GetTrigs(degrees, &sinang, &cosang);
   Move(cosang*cwidth + 0.5, sinang*cwidth+0.5);
   return err;
}


Figure 1. Clarus the dogcow is rotated through 30 degrees using RotatePixMap. DrawRotatedString is used to surround him with moofs.

Joseph J. Strout <joe@strout.net>

You can download a demo of this Tip from ftp://ftp.mactech.com/src.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Tor Browser 12.5.5 - Anonymize Web brows...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Malwarebytes 4.21.9.5141 - Adware remova...
Malwarebytes (was AdwareMedic) helps you get your Mac experience back. Malwarebytes scans for and removes code that degrades system performance or attacks your system. Making your Mac once again your... Read more
TinkerTool 9.5 - Expanded preference set...
TinkerTool is an application that gives you access to additional preference settings Apple has built into Mac OS X. This allows to activate hidden features in the operating system and in some of the... Read more
Paragon NTFS 15.11.839 - Provides full r...
Paragon NTFS breaks down the barriers between Windows and macOS. Paragon NTFS effectively solves the communication problems between the Mac system and NTFS. Write, edit, copy, move, delete files on... Read more
Apple Safari 17 - Apple's Web brows...
Apple Safari is Apple's web browser that comes bundled with the most recent macOS. Safari is faster and more energy efficient than other browsers, so sites are more responsive and your notebook... Read more
Firefox 118.0 - Fast, safe Web browser.
Firefox offers a fast, safe Web browsing experience. Browse quickly, securely, and effortlessly. With its industry-leading features, Firefox is the choice of Web development professionals and casual... Read more
ClamXAV 3.6.1 - Virus checker based on C...
ClamXAV is a popular virus checker for OS X. Time to take control ClamXAV keeps threats at bay and puts you firmly in charge of your Mac’s security. Scan a specific file or your entire hard drive.... Read more
SuperDuper! 3.8 - Advanced disk cloning/...
SuperDuper! is an advanced, yet easy to use disk copying program. It can, of course, make a straight copy, or "clone" - useful when you want to move all your data from one machine to another, or do a... Read more
Alfred 5.1.3 - Quick launcher for apps a...
Alfred is an award-winning productivity application for OS X. Alfred saves you time when you search for files online or on your Mac. Be more productive with hotkeys, keywords, and file actions at... Read more
Sketch 98.3 - Design app for UX/UI for i...
Sketch is an innovative and fresh look at vector drawing. Its intentionally minimalist design is based upon a drawing space of unlimited size and layers, free of palettes, panels, menus, windows, and... Read more

Latest Forum Discussions

See All

New ‘Marvel Snap’ Update Has Balance Adj...
As we wait for the information on the new season to drop, we shall have to content ourselves with looking at the latest update to Marvel Snap (Free). It’s just a balance update, but it makes some very big changes that combined with the arrival of... | Read more »
‘Honkai Star Rail’ Version 1.4 Update Re...
At Sony’s recently-aired presentation, HoYoverse announced the Honkai Star Rail (Free) PS5 release date. Most people speculated that the next major update would arrive alongside the PS5 release. | Read more »
‘Omniheroes’ Major Update “Tide’s Cadenc...
What secrets do the depths of the sea hold? Omniheroes is revealing the mysteries of the deep with its latest “Tide’s Cadence" update, where you can look forward to scoring a free Valkyrie and limited skin among other login rewards like the 2nd... | Read more »
Recruit yourself some run-and-gun royalt...
It is always nice to see the return of a series that has lost a bit of its global staying power, and thanks to Lilith Games' latest collaboration, Warpath will be playing host the the run-and-gun legend that is Metal Slug 3. [Read more] | Read more »
‘The Elder Scrolls: Castles’ Is Availabl...
Back when Fallout Shelter (Free) released on mobile, and eventually hit consoles and PC, I didn’t think it would lead to something similar for The Elder Scrolls, but here we are. The Elder Scrolls: Castles is a new simulation game from Bethesda... | Read more »
The best iOS games to get you in the Hal...
We’re getting closer and closer to Halloween every day, which means everyone’s gearing up to watch their favorite horror movies, make weekend trips out to pumpkin patches, and do all kinds of other, fun seasonal stuff before this month ends and... | Read more »
‘Final Fantasy VII: Ever Crisis’ New Ori...
Following its full worldwide launch, Square Enix’s Final Fantasy VII compendium game Final Fantasy VII: Ever Crisis (Free) for iOS and Android has just gotten its first major update. This update brings in a brand-new original story chapter only... | Read more »
‘Cypher 007’ Is Out Now on Apple Arcade...
This week’s new Apple Arcade release is Cypher 007 () from Tilting Point. Cypher 007 is an action adventure game inspired by 60 years of Spycraft from James Bond. It is the final Apple Arcade release of September, and quite a good way to end the... | Read more »
‘Capcom Town’ Digital Museum Website Upd...
Back in June, Capcom launched a 40th anniversary site to celebrate its anniversary with a digital museum that had five playable retro games. The Capcom Town website has just been updated to add in three more playable games. These retro games join... | Read more »
‘Subpar Pool’ from ‘Holedown’ Developer...
You don’t have to ask me twice to care about a new game from Swedish developer Grapefukt Games. Heck you don’t even have to ask me once. After bringing such classics as Holedown, Twofold Inc, and Rymdkapsel, I’m onboard for pretty much anything this... | Read more »

Price Scanner via MacPrices.net

Apple drops prices on refurbished 13-inch M2...
Apple has dropped prices on standard-configuration 13″ M2 MacBook Pros, Certified Refurbished, to as low as $1099 and ranging up to $230 off MSRP. These are the cheapest 13″ M2 MacBook Pros for sale... Read more
14-inch M2 Max MacBook Pro on sale for $300 o...
B&H Photo has the Space Gray 14″ 30-Core GPU M2 Max MacBook Pro in stock and on sale today for $2799 including free 1-2 day shipping. Their price is $300 off Apple’s MSRP, and it’s the lowest... Read more
Apple is now selling Certified Refurbished M2...
Apple has added a full line of standard-configuration M2 Max and M2 Ultra Mac Studios available in their Certified Refurbished section starting at only $1699 and ranging up to $600 off MSRP. Each Mac... Read more
New sale: 13-inch M2 MacBook Airs starting at...
B&H Photo has 13″ MacBook Airs with M2 CPUs in stock today and on sale for $200 off Apple’s MSRP with prices available starting at only $899. Free 1-2 day delivery is available to most US... Read more
Apple has all 15-inch M2 MacBook Airs in stoc...
Apple has Certified Refurbished 15″ M2 MacBook Airs in stock today starting at only $1099 and ranging up to $230 off MSRP. These are the cheapest M2-powered 15″ MacBook Airs for sale today at Apple.... Read more
In stock: Clearance M1 Ultra Mac Studios for...
Apple has clearance M1 Ultra Mac Studios available in their Certified Refurbished store for $540 off original MSRP. Each Mac Studio comes with Apple’s one-year warranty, and shipping is free: – Mac... Read more
Back on sale: Apple’s M2 Mac minis for $100 o...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $100 –... Read more
New low prices: Apple 14″ M2 Pro MacBook Pros...
B&H Photo has standard-configuration Apple 14″ M2 Pro MacBook Pros in stock today and on sale for $250-$300 off MSRP, each including free 1-2 day delivery to most US addresses: – 14″ 10-Core M2... Read more
9th-generation 10.2″ iPads on sale for $50-$6...
B&H Photo has Apple’s 9th generation 10.2″ WiFi iPads on sale for $50-$60 off MSRP with prices available starting at $269. Their prices are the lowest new prices available for iPads anywhere.... Read more
Apple has the iPad mini 6 in stock today for...
Apple has the 8.3″ WiFi iPad mini 6 in stock and available for $80-$100 off MSRP, Certified Refurbished, each including free shipping. Prices start at $419. Each iPad features a new outer case and... Read more

Jobs Board

Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Beauty Consultant - *Apple* Blossom Mall -...
Beauty Consultant - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Sales Floor Associate - *Apple* Blossom Mal...
Sales Floor Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Systems Administrator - *Apple* Devices / J...
…Description:** **Duties and Responsibilities** + Configure and maintain the client's Apple Device Management (ADM) solution. The current solution is JAMF supporting Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.