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

Visual Studio Code 1.70.0 - Cross-platfo...
Visual Studio Code provides developers with a new choice of developer tool that combines the simplicity and streamlined experience of a code editor with the best of what developers need for their... Read more
RapidWeaver 8.10.1 - Create template-bas...
RapidWeaver is a next-generation Web design application to help you easily create professional-looking Web sites in minutes. No knowledge of complex code is required, RapidWeaver will take care of... Read more
Tinderbox 9.3.0 - Store and organize you...
Tinderbox is a personal content management assistant. It stores your notes, ideas, and plans. It can help you organize and understand them. And Tinderbox helps you share ideas through Web journals... Read more
Dropbox 154.4.5363 - Cloud backup and sy...
Dropbox is a file hosting service that provides cloud storage, file synchronization, personal cloud, and client software. It is a modern workspace that allows you to get to all of your files, manage... Read more
SpamSieve 2.9.50 - Robust spam filter fo...
SpamSieve is a robust spam filter for major email clients that uses powerful Bayesian spam filtering. SpamSieve understands what your spam looks like in order to block it all, but also learns what... Read more
Butler 4.4.6 - Hot key, menu, and keywor...
Butler makes it easier for you to perform a wide variety of potentially recurring tasks. Just arrange these tasks in Butler's fully customizable configuration and assign one or more triggers to a... Read more
Nitro PDF Pro Essentials 13.3.0 - Edit a...
Nitro PDF Pro Essentials allows users to easily edit PDF's. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Even correct text and edit... Read more
Nitro PDF Pro 13.3.0 - Advanced PDF tool...
Nitro PDF Pro allows users to edit PDF's easily. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Create fillable forms and tables of... Read more
Evernote 10.42.7 - Create searchable not...
Evernote allows you to easily capture information in any environment using whatever device or platform you find most convenient, and makes this information accessible and searchable at anytime, from... Read more
Adobe Illustrator 26.4.1 - Professional...
You can download Adobe Illustrator for Mac as a part of Creative Cloud for only $20.99/month. Adobe Illustrator for Mac is the vector graphics classics in the design industry. It is a digital... Read more

Latest Forum Discussions

See All

Paying 75 Percent Attention – The TouchA...
After missing out on recording last week due to travel circumstances, we are back with a fresh episode of The TouchArcade Show! We kick things off with a bit about Eli’s trip to Chicago and the strange state of children’s programming on YouTube.... | Read more »
TouchArcade Game of the Week: ‘Card Craw...
Card Crawl from Tinytouchtales has remained a go-to game on my device since it released in 2015. It managed to be a fairly straightforward card-battling dungeon crawler game without selling itself short on strategy or variety. In 2017 a follow-up... | Read more »
SwitchArcade Round-Up: ‘Gigapocalypse’,...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for August 5th, 2022. It’s been quite the week for me, and I can’t say I’m unhappy to see it come to a close. We’ve got several new releases to look at today to close out the week, with... | Read more »
‘Hindsight’ Mobile Review – Beautiful Gr...
When Hindsight ($4.99), the new game from Prune developer Joel McDonald, was announced for multiple platforms, including iOS, I was pretty excited to experience it. Being published by Annapurna Interactive is usually a great sign, but what really... | Read more »
Northern Forge Studios announces their n...
Canadian developers Northern Forge Studios have announced the follow-up to the popular MMORPG Orna: the GPS RPG, called Hero of Aethric: An Orna RPG. Set in the same universe as its predecessor, Hero of Aetheric will expand the lore of the... | Read more »
The Brilliant ‘Papers, Please’ Is Out No...
Late last month, Lucas Pope announced that his award-winning “Dystopian Document Thriller" Papers, Please ($7.99) will be coming to iPhone and Android today following its debut on iOS back in 2014 on iPad. | Read more »
‘Amazing Bomberman’ Is Out Now As This W...
A few days ago, Apple revealed the four games joining Apple Arcade for this month. These included two originals and two App Store Greats. | Read more »
‘Stardew Valley’ 1.5 for Mobile Should B...
We’ve been covering the Stardew Valley ($4.99) massive version 1.5 update for a while now. It was previously confirmed to still be in the works for mobile following its launch on PC and console platforms. | Read more »
Mobile Fighting Game ‘Metal Revolution’...
In May of last year we checked in on Metal Revolution from GTArcade, a real-deal fighting game built from the ground up for mobile that had at that time already been in the works and various stages of testing for at least a couple of years. Our post... | Read more »
SwitchArcade Round-Up: ‘Pokemon’ News, ‘...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for August 4th, 2022. There’s a little bit of news to get us started today before we head into the new releases of the day. And it’s a good thing we have that news, because it’s a... | Read more »

Price Scanner via MacPrices.net

Apple Watch SE on sale for $50 off MSRP
Amazon has Apple Watch SE GPS models on sale for $50 off MSRP for a limited time, each including free shipping. Their prices are the lowest currently available for SE Watches: – 40mm Apple Watch SE... Read more
Save $310 on a 14″ 24-core GPU M1 Max MacBook...
Save $310 on 14″ MacBook Pros with 24-core M1 Max processors at Apple (32GB RAM/1TB SSD) with these Certified Refurbished models in stock today for $2789 in Space Gray or Silver colors. Regular price... Read more
14″ M1 Pro MacBook Pros available today at Ap...
Apple has Certified Refurbished standard-configuration 14″ MacBook Pros with M1 Pro CPUs available today for up to $250 off original MSRP, starting at $1799. Each model features a new outer case,... Read more
13″ MacBook Air with M2 CPU, in Starlight, on...
Apple retailer Expercom has the new Starlight 13″ MacBook Air with an M2 CPU (8GB RAM/256GB SSD) on sale for $1135.05, shipped, through August 12, 2022. Their price is $64 off Apple’s MSRP, and it’s... Read more
14″ M1 Pro MacBook Pro with 1TB SSD on sale f...
Expercom is offering a $200 instant discount on the 14″ M1 Pro MacBook Pro with a 1TB SSD through August 12, 2022. Their discount reduces the price of this configuration to $1999 shipped — the lowest... Read more
10″ 256GB WiFi iPads are on sale for $399, sa...
Amazon has new 10.2″ 9th generation 256GB WiFi iPads in stock and on sale today for $80 off Apple’s MSRP, only $399. Shipping is free. Note that stock (and prices) at Amazon can change quickly. These... Read more
13-inch M2 MacBook Pro with 512GB SSD on sale...
Amazon has the new 13″ Silver MacBook Pro with an M2 CPU and 512GB SSD in stock and on sale today for $1349 shipped. Their price is $150 off Apple’s MSRP. Be sure to purchase from Amazon rather than... Read more
Apple AirPods Max headphones are on sale for...
Verizon has Apple AirPods Max headphones on sale again for $100 off MSRP, only $449. Sale price is valid for all colors and is available online only. Choose free shipping when ordering or free local... Read more
64GB 4K Apple TV in stock and on sale for $13...
Amazon has 2nd generation 64GB 4K Apple TVs with Siri remotes in stock again and on sale for $60 off MSRP, only $139. That’s a 33% discount and the cheapest 64GB model available anywhere. Shipping is... Read more
New promos at Boost Mobile: iPhone 13 models...
Boost Mobile has Apple iPhone 13 models now on sale for $100 off MSRP with new lines of service. Their discount applies to 128GB and 256GB iPhone 13 Pro Max models, and 128GB, 256GB, & 512GB... Read more

Jobs Board

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
Sr Product Manager, *Apple* TV Platforms -...
…an experienced senior product manager to drive the strategy and requirements for our Apple TV devices, acting as the champion and owner of the holistic experience in Read more
Sr. *Apple* Endpoint Device Engineer - The...
IT APPLE ENDPOINT ENGINEER + Responsible for the management and administration of all Apple hardware including: building software packages/scripts, testing Read more
*Apple* MacOS Systems Administrator (Active...
…to detail. At GDIT, people are our differentiator. As a Systems Administrator supporting Apple MacOS and iOS systems and technologies, you will be trusted to provide Read more
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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.