创建一个NSView的子类. 然后根据需要创建自定义的view 来完成自定义画图和事件响应.
头文件:StretchView.h
#import <Cocoa/Cocoa.h>
@interface StretchView : NSView
{
NSBezierPath *path;
NSImage *image;
}
-(void) setImage:(NSImage *) newImage;
@end
源文件:StretchView.m
#import "StretchView.h"
@implementation StretchView
-(void) setImage:(NSImage *)newImage
{
[newImage retain];
[image release];
image = newImage;
[self setNeedsDisplay:YES];
}
-(id) initWithFrame:(NSRect)frameRect
{
[path closePath];
return self;
}
-(void) drawRect:(NSRect) rect
{
NSRect bounds = [self bounds];
[[NSColor greenColor] set];
[NSBezierPath fillRect:bounds];
[[NSColor whiteColor] set];
[path stroke];
NSBezierPath *path = [NSBezierPath bezierPath];
[path setLineWidth:2];
NSPoint startPoint = {0, 20};
NSPoint endPoint = { 100,20};
NSPoint secondPoint = {0,130};
NSPoint secondEndPoint ={100,130};
[path moveToPoint:startPoint];
[path lineToPoint:endPoint];
[path moveToPoint:secondPoint];
[path lineToPoint:secondEndPoint];
[[NSColor brownColor] set];
[path stroke];
NSRect r = NSMakeRect(0,1,100,150);
NSBezierPath *bp = [NSBezierPath bezierPathWithRect:r];
NSColor *color = [NSColor blueColor];
NSString *str = @" 11.png";
[str drawInRect:r withAttributes:NULL];
[color set];
[bp stroke];
NSRect downRect = NSMakeRect(0, 1, 100, 20);
NSString *downString =@" # 1";
[downString drawInRect:downRect withAttributes:nil];
if(image)
{
NSRect imageRect;
imageRect.origin = NSZeroPoint;
imageRect.size = [image size];
NSRect drawingRect = [self currentRect];
[image drawInRect:drawingRect
fromRect:imageRect
operation:NSCompositeSourceOver
fraction:1.0];
}
}
-(void) dealloc
{
[path release];
[image release];
[super dealloc];
}
-(NSRect) currentRect
{
return NSMakeRect(0, 0, 400, 400);
}
@end
头文件:AppController.h
#import <Cocoa/Cocoa.h>
@class StretchView;
@interface AppController : NSObject
{
IBOutlet StretchView *stretchView;
}
-(void)showImage;
@end
源文件:AppController.m
#import "AppController.h"
#import "StretchView.h"
@implementation AppController
-(void) showImage
{
NSString *path = @"Users/picture/11.png";
NSImage *image = [[NSImage alloc] initWithContentsOfFile:path];
[stretchView setImage:image];
[image release];
}
@end