Another newbie request.

Posts: 22
Joined: 2007.05
Post: #1
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):

- (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:

[nextCardImage setImage:[deck drawCard]];

nextCardImage is an NSImageView Outlet.

Thanks for any help.
Quote this message in a reply
Posts: 509
Joined: 2002.09
Post: #2
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

"When you dream, there are no rules..."
Quote this message in a reply
Posts: 22
Joined: 2007.05
Post: #3
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.

- (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];
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  [Request] Pong Source & One Question McSpider 6 10,227 Sep 18, 2011 07:21 AM
Last Post: fudog
  newbie request direction Teehee 3 8,606 Jul 27, 2011 09:57 AM
Last Post: AndyKorth