Daniel
Daniel

Reputation: 1087

NSImageView drawing incorrectly

I created a custom subclass of NSView in order to control 2 NSImageViews. The code for creating the images is as follows:

- (id)initWithFrame:(NSRect)frameRect AndMap:(NSImage *)map AndPlayer:(NSImage *)guyImage
{
    self = [super initWithFrame:frameRect];
    if (self)
    {
        NSRect newRect = NSMakeRect(0.0, 0.0, 64.0, 64.0);

        NSImageView *theMap = [[NSImageView alloc] initWithFrame:NSMakeRect(0.0, 0.0, frameRect.size.width, frameRect.size.height)];
        [theMap setImage:map];

        NSImageView *theGuy = [[NSImageView alloc] initWithFrame:newRect];
        [theGuy setImage:guyImage];

        [self setMapImage:theMap];
        [self setPlayerView:theGuy];
        [self addSubview:[self mapImage]];
        [self addSubview:[self playerView]];

However, when I tell the view to draw in a rect with origin (128,0), it draws theMap with a weird offsets, so that theGuy's origin is at 128,0, but theMap's origin is at something like (128,20). I can't find any reason why this should occur.

Upvotes: 0

Views: 459

Answers (2)

user557219
user557219

Reputation:

My guess is that you have overlapping sibling views:

  • theMap has frame {{0.0, 0.0}, {frameRect.size.width, frameRect.size.height}}
  • theGuy has frame {{0.0, 0.0}, {64.0, 64.0}}
  • both theMap and theGuy are (or seem to be) added to the same superview, namely self, and have the same origin.

Cocoa doesn’t guarantee correct behaviour for overlapping sibling views, i.e., two views that have the same direct superview and whose corresponding frames overlap. From the View Programming Guide:

Note: For performance reasons, Cocoa does not enforce clipping among sibling views or guarantee correct invalidation and drawing behavior when sibling views overlap. If you want a view to be drawn in front of another view, you should make the front view a subview (or descendant) of the rear view.

According to this answer to another question on Stack Overflow, one alternative solution is to turn on layers for the views.

Upvotes: 2

Ken
Ken

Reputation: 31161

Quick thought - are the strange map offsets not accidentally part of the map NSImage?

Upvotes: 0

Related Questions