You need to log in to create posts and topics.
Tutorial_5
1,678 Posts
#1 · September 4, 2011, 11:32 am
Quote from Forum Archives on September 4, 2011, 11:32 amPosted by: svanvoorst <svanvoorst@...>
After you've created your masterpiece in NSView you may want to print it, as demonstrated below. To make things more interesting I have embedded two buttons in the view: "Print" and "Quit". Everything in the view is printed, including the buttons, which we probably don't want to see in the final output. To avoid printing the buttons: 1) retain them to prevent loss, 2) remove them from the Superview, and 3) restore them after the printing has been done. This demo prints from a button via a controller using NSPrintInfo and NSPrintOperation. Several settings allow for good control of the output. It is also possible to print from a menu item using cmd-P, without any print routine being provided. However, the output is a bitmap type image of the entire window and is not satisfactory in my opinion.The demo also shows how to create "outlets". In XCode, we just preface our intended outlet with -(IBOutlet) and Interface Builder automatically makes them available so that we can drag our connections. Since we are not using a nib for this technique and need the id of our view and controls available to the print routine, I have had to rely on what I am labeling as globals. I'm not sure that they are truly globals since I have not had the need to use them outside of this one implementation section. At any rate, I have used the lower case "g" to designate that they are the id of the drawing view and buttons, initially introduced in the main section of the code. There may be a better or more correct way, but it works. There is nothing magic about the "g" and another designation might make more sense and potentially avoid the wrath of those allergic to it.I will probably hold off on publishing more demos until you have had time to digest these. Give it a try and see if you can create small apps with this technique. I suggest keeping it simple in the beginning until you get the hang of it. FB has been a blessing for me because it has allowed me to get a foot in the door without using XCode/IB. It's sort of like a sixteen year old trying to learn how to drive and someone hands them the keys to a 500 hp, turbocharged vehicle. It's just a little more car than they can safely handle. In a couple of years, maybe. In FB it won't get done unless you code for it. There are not a lot of automatic features which leave you scratching your head. It is a good way to learn the basics.'------ start -------///////////////////////////////////////// FBtoC Preferences Settings: //// Requires 10.6 Base SDK //// Compile As Objective-C checked //// or Un-REM first line below ///////////////////////////////////////////compile as "Objective-C"BeginCDeclaration// Create controller class@interface AppController : NSObject{}- (void)printView:(id)sender;@end //interfaceEndCBeginCFunction@implementation AppController// These are used in lieu of outlets.id gQuitBtnID;id gPrintBtnID;id gDrawViewID;- (void)printView:(id)sender{NSPrintInfo *printInfo = [NSPrintInfo sharedPrintInfo];[printInfo setVerticallyCentered:NO];[printInfo setHorizontallyCentered:YES];[printInfo setTopMargin:60];[printInfo setBottomMargin:10];[printInfo setLeftMargin:45];[printInfo setRightMargin:45];[printInfo setOrientation:NSPortraitOrientation];NSPrintOperation *printOp;printOp = [NSPrintOperation printOperationWithView:gDrawViewID printInfo:printInfo];//[printOp setShowsPrintPanel:YES];//--Temporarily remove buttons overlying DrawView ---[gPrintBtnID retain];[gPrintBtnID removeFromSuperview];[gQuitBtnID retain];[gQuitBtnID removeFromSuperview];//-- Run print operation ---[printOp runOperation];// -- Restore buttons ---[gDrawViewID addSubview:gPrintBtnID];[gDrawViewID addSubview:gQuitBtnID];}@endEndCBeginCDeclaration@interface DrawView : NSView//methods automatically called@end //interfaceEndCBeginCFunction@implementation DrawView : NSView;- (id)initWithFrame:(NSRect)frameRect{if ((self = [super initWithFrame:frameRect]) != nil){self = [super initWithFrame:frameRect];// Add initialization code here}return self;}- (void)drawRect:(NSRect)rect{// ****** Filled Background ***** //[[NSColor whiteColor] set];[NSBezierPath fillRect:rect];// ****** Attributed text ****** //NSString *myStr;NSPoint myPt;NSMutableDictionary *attr = [NSMutableDictionary dictionary];[attr setObject:[NSFont fontWithName:@"Lucida Grande" size:18] forKey:NSFontAttributeName];myStr = @"Attributed Text Drawn in an NSView";myPt = NSMakePoint(30,20);[myStr drawAtPoint:myPt withAttributes:attr];[NSBezierPath setDefaultLineWidth:3.0];// ****** Line ****** //NSPoint begin, end;begin = NSMakePoint( 30, 50 );end = NSMakePoint( 360, 50 );[NSBezierPath strokeLineFromPoint: begin toPoint:end];// ***** Hashed Line ****** //float lineDash[1];NSBezierPath *hash = [NSBezierPath bezierPath];[hash moveToPoint:NSMakePoint( 30, 70 )];[hash lineToPoint:NSMakePoint( 360, 70 )];lineDash[0] = 10; //dashlineDash[1] = 4; //gap[hash setLineDash:lineDash count: 2 phase:0.0 ];[hash stroke];// ****** Rounded Rectangle ****** //NSRect R = NSMakeRect(100, 100, 100, 100);[[NSColor greenColor] set];NSBezierPath *parr = [NSBezierPath bezierPath];[parr appendBezierPathWithRoundedRect: R xRadius: 10.0 yRadius: 10.0 ];[parr stroke];// ****** Circle ****** //NSRect dotR = NSMakeRect( rect.size.width/2 - 50, rect.size.height/2 - 80, 100, 100 );[[NSColor redColor] set];[[NSBezierPath bezierPathWithOvalInRect:dotR] fill];// ****** Oval ****** //NSRect ovalR = NSMakeRect( 100, 230, 200, 100 );[[NSColor magentaColor] set];[[NSBezierPath bezierPathWithOvalInRect:ovalR] fill];// ***** Polygon ****** //[[NSColor blackColor] set];NSBezierPath *path = [NSBezierPath bezierPath];[path moveToPoint: NSMakePoint( 220.0, 150.0 )];[path lineToPoint: NSMakePoint( 245.0, 175.0 )];[path lineToPoint: NSMakePoint( 270.0, 150.0 )];[path lineToPoint: NSMakePoint( 295.0, 150.0 )];[path lineToPoint: NSMakePoint( 250.0, 120.0 )];[path lineToPoint: NSMakePoint( 220.0, 150.0 )];[path closePath];[path setLineJoinStyle: NSRoundLineJoinStyle];[path stroke];NSRect outer = NSMakeRect( 80, 310, 100, 50 );NSRect inner = NSInsetRect( outer, 1, 1 );// ****** Filled Rectangle ***** //[[NSColor blueColor] set];[NSBezierPath fillRect:inner];// ****** Stroked Rectangle ****** //[[NSColor grayColor] set];[NSBezierPath strokeRect:outer];// ******Arc ******* //[[NSColor blackColor] set];NSBezierPath *arc = [NSBezierPath bezierPath];[arc moveToPoint:NSMakePoint( 200, 320 )];[arc appendBezierPathWithArcFromPoint:NSMakePoint( 200, 380 ) toPoint:NSMakePoint( 260, 380 ) radius:60];[arc stroke];}-(BOOL)isFlipped{return YES;}@end //implementationEndCBeginCCode{NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];[NSApplication sharedApplication];[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];// Create an instance of the controller classid myController = [[AppController alloc]init];// ----- Menubar and Menu ---- //id menubar = [[NSMenu new] autorelease];id appMenuItem = [[NSMenuItem new] autorelease];[menubar addItem:appMenuItem];[NSApp setMainMenu:menubar];id appMenu = [[NSMenu new] autorelease];id quitMenuItem = [[[NSMenuItem alloc] initWithTitle:@"Quit"action:@selector(terminate:) keyEquivalent:@"q"] autorelease];[appMenu addItem:quitMenuItem];[appMenuItem setSubmenu:appMenu];//----- Window ---- //#define _wndW 440#define _wndH 500id window = [ [ NSWindow alloc ]initWithContentRect:NSMakeRect( 0, 0, _wndW, _wndH )styleMask: NSClosableWindowMask | NSTitledWindowMaskbacking:NSBackingStoreBuffereddefer:NO];[window center];[window setTitle: @"NSView_demo" ];[window makeKeyAndOrderFront:nil];// ------- Create an instance of DrawView (NSView) ------ //id myDrawView = [[DrawView alloc]initWithFrame:NSMakeRect( 20, 20, _wndW - 40, _wndH - 40 )];[[window contentView] addSubview:myDrawView];gDrawViewID = myDrawView;[myDrawView release];NSButton *quitBtn = [[NSButton alloc]initWithFrame:NSMakeRect( _wndW - 160, _wndH - 80, 100, 30 )];[quitBtn setBezelStyle:NSRoundedBezelStyle ];[quitBtn setTitle: @"Quit" ];[quitBtn setAction:@selector(terminate:)];[myDrawView addSubview: quitBtn];gQuitBtnID = quitBtn;[quitBtn release];NSButton *printBtn = [[NSButton alloc]initWithFrame:NSMakeRect( _wndW - 260, _wndH - 80, 100, 30 )];[printBtn setBezelStyle:NSRoundedBezelStyle ];[printBtn setTitle: @"Print" ];[printBtn setTarget:myController];[printBtn setAction:@selector(printView:)];[myDrawView addSubview: printBtn];gPrintBtnID = printBtn;[printBtn release];[NSApp activateIgnoringOtherApps:YES];[NSApp run];[myController release];[pool drain];}EndC
'----- end ---------Steve Van Voorst
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
Posted by: svanvoorst <svanvoorst@...>
After you've created your masterpiece in NSView you may want to print it, as demonstrated below. To make things more interesting I have embedded two buttons in the view: "Print" and "Quit". Everything in the view is printed, including the buttons, which we probably don't want to see in the final output. To avoid printing the buttons: 1) retain them to prevent loss, 2) remove them from the Superview, and 3) restore them after the printing has been done. This demo prints from a button via a controller using NSPrintInfo and NSPrintOperation. Several settings allow for good control of the output. It is also possible to print from a menu item using cmd-P, without any print routine being provided. However, the output is a bitmap type image of the entire window and is not satisfactory in my opinion.
The demo also shows how to create "outlets". In XCode, we just preface our intended outlet with -(IBOutlet) and Interface Builder automatically makes them available so that we can drag our connections. Since we are not using a nib for this technique and need the id of our view and controls available to the print routine, I have had to rely on what I am labeling as globals. I'm not sure that they are truly globals since I have not had the need to use them outside of this one implementation section. At any rate, I have used the lower case "g" to designate that they are the id of the drawing view and buttons, initially introduced in the main section of the code. There may be a better or more correct way, but it works. There is nothing magic about the "g" and another designation might make more sense and potentially avoid the wrath of those allergic to it.
I will probably hold off on publishing more demos until you have had time to digest these. Give it a try and see if you can create small apps with this technique. I suggest keeping it simple in the beginning until you get the hang of it. FB has been a blessing for me because it has allowed me to get a foot in the door without using XCode/IB. It's sort of like a sixteen year old trying to learn how to drive and someone hands them the keys to a 500 hp, turbocharged vehicle. It's just a little more car than they can safely handle. In a couple of years, maybe. In FB it won't get done unless you code for it. There are not a lot of automatic features which leave you scratching your head. It is a good way to learn the basics.
'------ start -------
///////////////////////////////////////
// FBtoC Preferences Settings: //
// Requires 10.6 Base SDK //
// Compile As Objective-C checked //
// or Un-REM first line below //
///////////////////////////////////////
//compile as "Objective-C"
BeginCDeclaration
// Create controller class
@interface AppController : NSObject
{
}
- (void)printView:(id)sender;
@end //interface
EndC
BeginCFunction
@implementation AppController
// These are used in lieu of outlets.
id gQuitBtnID;
id gPrintBtnID;
id gDrawViewID;
- (void)printView:(id)sender
{
NSPrintInfo *printInfo = [NSPrintInfo sharedPrintInfo];
[printInfo setVerticallyCentered:NO];
[printInfo setHorizontallyCentered:YES];
[printInfo setTopMargin:60];
[printInfo setBottomMargin:10];
[printInfo setLeftMargin:45];
[printInfo setRightMargin:45];
[printInfo setOrientation:NSPortraitOrientation];
NSPrintOperation *printOp;
printOp = [NSPrintOperation printOperationWithView:gDrawViewID printInfo:printInfo];
//[printOp setShowsPrintPanel:YES];
//--Temporarily remove buttons overlying DrawView ---
[gPrintBtnID retain];
[gPrintBtnID removeFromSuperview];
[gQuitBtnID retain];
[gQuitBtnID removeFromSuperview];
//-- Run print operation ---
[printOp runOperation];
// -- Restore buttons ---
[gDrawViewID addSubview:gPrintBtnID];
[gDrawViewID addSubview:gQuitBtnID];
}
@end
EndC
BeginCDeclaration
@interface DrawView : NSView
//methods automatically called
@end //interface
EndC
BeginCFunction
@implementation DrawView : NSView;
- (id)initWithFrame:(NSRect)frameRect
{
if ((self = [super initWithFrame:frameRect]) != nil)
{
self = [super initWithFrame:frameRect];
// Add initialization code here
}
return self;
}
- (void)drawRect:(NSRect)rect
{
// ****** Filled Background ***** //
[[NSColor whiteColor] set];
[NSBezierPath fillRect:rect];
// ****** Attributed text ****** //
NSString *myStr;
NSPoint myPt;
NSMutableDictionary *attr = [NSMutableDictionary dictionary];
[attr setObject:[NSFont fontWithName:@"Lucida Grande" size:18] forKey:NSFontAttributeName];
myStr = @"Attributed Text Drawn in an NSView";
myPt = NSMakePoint(30,20);
[myStr drawAtPoint:myPt withAttributes:attr];
[NSBezierPath setDefaultLineWidth:3.0];
// ****** Line ****** //
NSPoint begin, end;
begin = NSMakePoint( 30, 50 );
end = NSMakePoint( 360, 50 );
[NSBezierPath strokeLineFromPoint: begin toPoint:end];
// ***** Hashed Line ****** //
float lineDash[1];
NSBezierPath *hash = [NSBezierPath bezierPath];
[hash moveToPoint:NSMakePoint( 30, 70 )];
[hash lineToPoint:NSMakePoint( 360, 70 )];
lineDash[0] = 10; //dash
lineDash[1] = 4; //gap
[hash setLineDash:lineDash count: 2 phase:0.0 ];
[hash stroke];
// ****** Rounded Rectangle ****** //
NSRect R = NSMakeRect(100, 100, 100, 100);
[[NSColor greenColor] set];
NSBezierPath *parr = [NSBezierPath bezierPath];
[parr appendBezierPathWithRoundedRect: R xRadius: 10.0 yRadius: 10.0 ];
[parr stroke];
// ****** Circle ****** //
NSRect dotR = NSMakeRect( rect.size.width/2 - 50, rect.size.height/2 - 80, 100, 100 );
[[NSColor redColor] set];
[[NSBezierPath bezierPathWithOvalInRect:dotR] fill];
// ****** Oval ****** //
NSRect ovalR = NSMakeRect( 100, 230, 200, 100 );
[[NSColor magentaColor] set];
[[NSBezierPath bezierPathWithOvalInRect:ovalR] fill];
// ***** Polygon ****** //
[[NSColor blackColor] set];
NSBezierPath *path = [NSBezierPath bezierPath];
[path moveToPoint: NSMakePoint( 220.0, 150.0 )];
[path lineToPoint: NSMakePoint( 245.0, 175.0 )];
[path lineToPoint: NSMakePoint( 270.0, 150.0 )];
[path lineToPoint: NSMakePoint( 295.0, 150.0 )];
[path lineToPoint: NSMakePoint( 250.0, 120.0 )];
[path lineToPoint: NSMakePoint( 220.0, 150.0 )];
[path closePath];
[path setLineJoinStyle: NSRoundLineJoinStyle];
[path stroke];
NSRect outer = NSMakeRect( 80, 310, 100, 50 );
NSRect inner = NSInsetRect( outer, 1, 1 );
// ****** Filled Rectangle ***** //
[[NSColor blueColor] set];
[NSBezierPath fillRect:inner];
// ****** Stroked Rectangle ****** //
[[NSColor grayColor] set];
[NSBezierPath strokeRect:outer];
// ******Arc ******* //
[[NSColor blackColor] set];
NSBezierPath *arc = [NSBezierPath bezierPath];
[arc moveToPoint:NSMakePoint( 200, 320 )];
[arc appendBezierPathWithArcFromPoint:NSMakePoint( 200, 380 ) toPoint:NSMakePoint( 260, 380 ) radius:60];
[arc stroke];
}
-(BOOL)isFlipped
{
return YES;
}
@end //implementation
EndC
BeginCCode
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
[NSApplication sharedApplication];
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
// Create an instance of the controller class
id myController = [[AppController alloc]init];
// ----- Menubar and Menu ---- //
id menubar = [[NSMenu new] autorelease];
id appMenuItem = [[NSMenuItem new] autorelease];
[menubar addItem:appMenuItem];
[NSApp setMainMenu:menubar];
id appMenu = [[NSMenu new] autorelease];
id quitMenuItem = [[[NSMenuItem alloc] initWithTitle:@"Quit"
action:@selector(terminate:) keyEquivalent:@"q"] autorelease];
[appMenu addItem:quitMenuItem];
[appMenuItem setSubmenu:appMenu];
//----- Window ---- //
#define _wndW 440
#define _wndH 500
id window = [ [ NSWindow alloc ]
initWithContentRect:NSMakeRect( 0, 0, _wndW, _wndH )
styleMask: NSClosableWindowMask | NSTitledWindowMask
backing:NSBackingStoreBuffered
defer:NO];
[window center];
[window setTitle: @"NSView_demo" ];
[window makeKeyAndOrderFront:nil];
// ------- Create an instance of DrawView (NSView) ------ //
id myDrawView = [[DrawView alloc]initWithFrame:NSMakeRect( 20, 20, _wndW - 40, _wndH - 40 )];
[[window contentView] addSubview:myDrawView];
gDrawViewID = myDrawView;
[myDrawView release];
NSButton *quitBtn = [[NSButton alloc]initWithFrame:NSMakeRect( _wndW - 160, _wndH - 80, 100, 30 )];
[quitBtn setBezelStyle:NSRoundedBezelStyle ];
[quitBtn setTitle: @"Quit" ];
[quitBtn setAction:@selector(terminate:)];
[myDrawView addSubview: quitBtn];
gQuitBtnID = quitBtn;
[quitBtn release];
NSButton *printBtn = [[NSButton alloc]initWithFrame:NSMakeRect( _wndW - 260, _wndH - 80, 100, 30 )];
[printBtn setBezelStyle:NSRoundedBezelStyle ];
[printBtn setTitle: @"Print" ];
[printBtn setTarget:myController];
[printBtn setAction:@selector(printView:)];
[myDrawView addSubview: printBtn];
gPrintBtnID = printBtn;
[printBtn release];
[NSApp activateIgnoringOtherApps:YES];
[NSApp run];
[myController release];
[pool drain];
}
EndC
'----- end ---------
Steve Van Voorst
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
Click for thumbs down.0Click for thumbs up.0