Sunday, May 27, 2012

View with no window


Scott Stevenson has two great posts about tutorials on drawing in Quartz 2D (here and here). I used his code to draw the graphic above.

One issue I've had was whether it's really necessary to use Core Graphics to draw to PDF from a command-line app. It's not, as this code shows. Thanks to a Stack Overflow answer for help.

// clang prog.m -o prog -framework Cocoa -fobjc-gc-only
#import <Cocoa/Cocoa.h>
//#import <AppKit/AppKit.h>

@interface MyView : NSView
@end

@implementation MyView
- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    }   
    return self;
}

- (void)drawRect:(NSRect)dirtyRect
{

// just paste Scott Stevenson's code here    
    
}
@end

int main(int argc, char * argv[]) {
    MyView *myView;
    NSRect f = NSMakeRect(0,0,400,400);
    myView = [[MyView alloc] initWithFrame:f];
    NSData *data = [myView dataWithPDFInsideRect:f];
    [data writeToFile:@"x.pdf" atomically:YES];
    return 0;
}