Images and Mouse Events(Chapter 18 of Cocoa Programming for Mac OS X)
1 #import “ StretchView.h “
2
3
4 @implementation StretchView
5
6 - (id)initWithFrame:(NSRect)rect
7 {
8 if ( ! [super initWithFrame:rect])
9 {
10 return nil;
11 }
12
13 srandom(time(NULL));
14
15 path = [[NSBezierPath alloc] init];
16 [path setLineWidth: 3.0 ];
17 NSPoint p = [self randomPoint];
18 [path moveToPoint:p];
19 int i;
20 for (i = 0 ;i < 15 ;i ++ )
21 {
22 p = [self randomPoint];
23 [path lineToPoint:p];
24 }
25 [path closePath];
26 opacity = 1.0 ;
27 return self;
28 }
29
30 - ( void )dealloc
31 {
32 [path release];
33 [image release];
34 [super dealloc];
35 }
36
37 - (NSPoint)randomPoint
38 {
39 NSPoint result;
40 NSRect r = [self bounds];
41 result.x = r.origin.x + random() % ( int )r.size.width;
42 result.y = r.origin.y + random() % ( int )r.size.height;
43 return result;
44 }
45
46 - ( void )drawRect:(NSRect)dirtyRect
47 {
48 NSRect bounds = [self bounds];
49 [[NSColor greenColor] set ];
50 [NSBezierPath fillRect:bounds];
51
52 [[NSColor whiteColor] set ];
53 [path fill];
54 if (image)
55 {
56 NSRect imageRect;
57 imageRect.origin = NSZeroPoint;
58 imageRect.size = [image size];
59 NSRect drawingRect = [self currentRect];
60 [image drawInRect:drawingRect fromRect:imageRect operation:NSCompositeSourceOver fraction:opacity];
61 }
62 }
63
64 - ( void )mouseDown:(NSEvent * ) event
65 {
66 NSPoint p = [ event locationInWindow];
67 downPoint = [self convertPoint:p fromView:nil];
68 currentPoint = downPoint;
69 [self setNeedsDisplay:YES];
70 NSLog( @” mouseDown: %d “ , [ event clickCount]);
71 }
72
73 - ( void )mouseDragged:(NSEvent * ) event
74 {
75 NSPoint p = [ event locationInWindow];
76 currentPoint = [self convertPoint:p fromView:nil];
77 [self setNeedsDisplay:YES];
78 NSLog( @” mouseDragged: %@ “ , NSStringFromPoint(p));
79 }
80
81 - ( void )mouseUp:(NSEvent * ) event
82 {
83 NSPoint p = [ event locationInWindow];
84 currentPoint = [self convertPoint:p fromView:nil];
85 [self setNeedsDisplay:YES];
86 NSLog( @” mouseUp: “ );
87 }
88
89 - (NSRect)currentRect
90 {
91 float minX = MIN(downPoint.x, currentPoint.x);
92 float maxX = MAX(downPoint.x, currentPoint.x);
93 float minY = MIN(downPoint.y, currentPoint.y);
94 float maxY = MIN(downPoint.y, currentPoint.y);
95
96 return NSMakeRect(minX, minY, maxX - minX, maxY - minY);
97 }
98
99 #pragma mark Accesors
100
101 - ( void )setImage:(NSImage * )newImage
102 {
103 [newImage retain];
104
105 [image release];
106 image = newImage;
107 NSSize imageSize = [newImage size];
108 downPoint = NSZeroPoint;
109 currentPoint.x = downPoint.x + imageSize.width;
110 currentPoint.y = downPoint.y + imageSize.height;
111 [self setNeedsDisplay:YES];
112 }
113
114 - ( float )opacity
115 {
116 return opacity;
117 }
118
119 - ( void )setOpacity:( float )x
120 {
121 opacity = x;
122 [self setNeedsDisplay:YES];
123 }
124
125 @end
转载于//www.cnblogs.com/zhtf2014/archive/2011/02/24/1963988.html
还没有评论,来说两句吧...