iDevGames Forums
Another newbie request. - Printable Version

+- iDevGames Forums (http://www.idevgames.com/forums)
+-- Forum: Development Zone (/forum-3.html)
+--- Forum: Game Programming Fundamentals (/forum-7.html)
+--- Thread: Another newbie request. (/thread-3255.html)



Another newbie request. - hypnotx - Jun 8, 2007 08:57 PM

Can anyone point me to some sample code that illustrates:

1.) Drawing a partial segment of a source image (png) to an NSImageView
2.) Drawing a partial segment of a source image (png) to a Custom View

Here is a little of what I am trying to get to work (using the NSImageView approach):

Code:
- (NSImage *)drawCard
{
    NSImage * cardSheet = [[NSImage alloc] initWithContentsOfFile:@"cardSheet.png"];
    
    NSSize cardInSheetSize;
    cardInSheetSize.height = 70;
    cardInSheetSize.width = 50;
    
    NSRect srcRect;
    (srcRect.origin).x = 0.0;
    (srcRect.origin).y = 0.0;
    srcRect.size = cardInSheetSize;
    
    NSRect dstRect;
    dstRect.origin = NSZeroPoint;
    dstRect.size = cardInSheetSize;
    
    NSImage * card = [[NSImage alloc] initWithSize:cardInSheetSize];
    [card lockFocus];
    [cardSheet drawInRect:dstRect fromRect:srcRect operation:NSCompositeCopy fraction:1.0];
    [card unlockFocus];
    
    return card;
}

I am calling it with:

Code:
[nextCardImage setImage:[deck drawCard]];

nextCardImage is an NSImageView Outlet.

Thanks for any help.


Another newbie request. - Taxxodium - Jun 9, 2007 01:13 AM

You are leaking memory badly. Before returning, release cardSheet and at the end do return [card autorelease]

Maybe it's better to use drawAtPoint or one of the composite methods. drawInRect is good, but you'll need to:

a) read what the docs say
b) experiment to get it right


Another newbie request. - hypnotx - Jun 10, 2007 02:03 AM

Still playing around with it but now using a Custom View. Came up with this after looking at the Quartz tutorials on Dev Central but it is still a work in progress. I most certainly need to reread the sections on memory management. I'm guessing that I can define an NSRect for the portion of the source image and pass that as the fromRect variable to drawInRect instead of NSZeroRect. I think I am almost there.

Code:
- (void)drawRect:(NSRect)rect
{
    // lets put an image in there.
    [[NSGraphicsContext currentContext] setImageInterpolation: NSImageInterpolationHigh];
    NSRect desRect = NSMakeRect(52, 1, 50, 70);
    
//      Next line wont work because it loads the entire sheet into the card rect.
//    Need to create a srcRect (see below) and pull the image from a portion of the source CardSheet.png.
//    NSString * file = @"/CardSheet.png";
    
    NSRect srcRect = NSMakeRect(0, 0, 50, 70);
    
    NSString * file = @"/singCard.png";
    NSImage * cardImage = [[NSImage alloc] initWithContentsOfFile:file];
    [cardImage drawInRect:desRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
    [cardImage release];
}