MenuItemView/ImageMenuItemView.m

/*
 Copyright (C) 2017 Apple Inc. All Rights Reserved.
 See LICENSE.txt for this sample’s licensing information
 
 Abstract:
 The NSView that draws a picture as its background, used for menu item views that want a background image.
 */
 
#import "ImageMenuItemView.h"
 
@interface ImageMenuItemView ()
 
@property (strong) NSImage *myImage;
 
@end
 
#pragma mark -
 
@implementation ImageMenuItemView
 
// -------------------------------------------------------------------------------
//  awakeFromNib:
// -------------------------------------------------------------------------------
- (void)awakeFromNib
{
    [super awakeFromNib];
    [self setupBackgroundImage];
}
 
// -------------------------------------------------------------------------------
//  setupBackgroundImage:
//
//  Setup the picture background for this view.
// -------------------------------------------------------------------------------
- (void)setupBackgroundImage
{
    // load the image to draw in the view's background, if not already allocated
    if (self.myImage == nil)
    {
        _myImage = [NSImage imageNamed:@"LakeDonPedro"];
    }
}
 
// -------------------------------------------------------------------------------
//  drawRect:rect
// -------------------------------------------------------------------------------
- (void)drawRect:(NSRect)rect
{   
    // draw the image for this view's background
    [self.myImage drawInRect:NSMakeRect(self.bounds.origin.x, self.bounds.origin.y, self.frame.size.width, self.frame.size.height)
                    fromRect:NSMakeRect(0, 0, self.myImage.size.width, self.myImage.size.height)
                   operation:NSCompositingOperationCopy
                    fraction:1.0];
}
 
@end