drawRect not drawing NSImage

855 Views Asked by At

I have a custom NSView

.h-file

#import <Cocoa/Cocoa.h>

@interface CustomView : NSView

@property BOOL shallDraw;

- (void) setTheShallDraw:(BOOL)draw;

@end

.m-file

#import "CustomView.h"

@implementation CustomView


- (id) initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
        _shallDraw = NO;


    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect
{
    [super drawRect:dirtyRect];

    // Drawing code here.


    if (_shallDraw) {

        NSLog(@"Drawing image");
        NSString * file = @"/Users/mac2/Desktop/Test 1.jpg";
        NSImage * image = [[NSImage alloc] initWithContentsOfFile:file];

        if (image) {
            NSLog(@"Image initialized");
        }

        [image setFlipped:NO];

        NSSize customViewSize = NSMakeSize(self.bounds.size.width, self.bounds.size.height);
        NSRect myRect = NSMakeRect(20, 20, customViewSize.height *5/7, customViewSize.height);

        // Set Image Size to Rect Size
        [image setSize:myRect.size];

        // Draw Image in Rect
        [image drawInRect: myRect
                     fromRect: NSZeroRect
                    operation: NSCompositeSourceOver
                     fraction: 1.0];
    }



}

- (void) setTheShallDraw:(BOOL)draw{
    _shallDraw = draw;
    NSLog(@"Method 1 called");
    [self setNeedsDisplay:YES];
}

and a controller class

.h

#import <Foundation/Foundation.h>
#import "CustomView.h"

@interface Controller : NSObject
- (IBAction)goButton:(id)sender;
@end

.m

#import "Controller.h"

@implementation Controller
- (IBAction)goButton:(id)sender {

    CustomView *cv = [[CustomView alloc]init];
    [cv setTheShallDraw:YES];

}

@end

I now want to call setTheShallDraw of the NSView from my controller in order to display an NSImage within a rect.

My Problem is, that although the method setTheShallDraw gets called, the drawRect method doesn't draw the image. What exactly am I missing?

This is just an experimental project, I need this for a more complex project involving composite images, so just using an NSImageView in IB won't do the trick.

2

There are 2 best solutions below

2
On

In your code, you don't add your CustomView instance to the view hierarchy...

- (IBAction)goButton:(id)sender {

    CustomView *cv = [[CustomView alloc]init];

    // add CustomView to view hierarchy
    [theContentView addSubview:cv];

    [cv setTheShallDraw:YES];
}
4
On

drawRect: gets called before the call [cv setTheShallDraw:YES]; happens.

Hence in the initWithFrame: the _shallDraw = NO; restricts to draw as you have:

 if (_shallDraw) {
    NSLog(@"Drawing image");