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 (!)
9 {
10 return nil;
11 }
12
13 srandom(time(NULL));
14
15 path = [ init];
16 ;
17 NSPoint p = ;
18 ;
19 int i;
20 for(i=0;i<15;i++)
21 {
22 p = ;
23 ;
24 }
25 ;
26 opacity = 1.0;
27 return self;
28 }
29
30 - (void)dealloc
31 {
32 ;
33 ;
34 ;
35 }
36
37 - (NSPoint)randomPoint
38 {
39 NSPoint result;
40 NSRect r = ;
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 = ;
49 [ set];
50 ;
51
52 [ set];
53 ;
54 if(image)
55 {
56 NSRect imageRect;
57 imageRect.origin = NSZeroPoint;
58 imageRect.size = ;
59 NSRect drawingRect = ;
60 ;
61 }
62 }
63
64 - (void)mouseDown:(NSEvent *)event
65 {
66 NSPoint p =;
67 downPoint = ;
68 currentPoint = downPoint;
69 ;
70 NSLog(@"mouseDown: %d", );
71 }
72
73 - (void)mouseDragged:(NSEvent *)event
74 {
75 NSPoint p = ;
76 currentPoint = ;
77 ;
78 NSLog(@"mouseDragged: %@", NSStringFromPoint(p));
79 }
80
81 - (void)mouseUp:(NSEvent *)event
82 {
83 NSPoint p = ;
84 currentPoint = ;
85 ;
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 ;
104
105 ;
106 image = newImage;
107 NSSize imageSize = ;
108 downPoint = NSZeroPoint;
109 currentPoint.x = downPoint.x + imageSize.width;
110 currentPoint.y = downPoint.y + imageSize.height;
111 ;
112 }
113
114 - (float)opacity
115 {
116 return opacity;
117 }
118
119 - (void)setOpacity:(float)x
120 {
121 opacity = x;
122 ;
123 }
124
125 @end
页:
[1]