views:

31

answers:

1

I have an NSView that display an image, and i'd like to make this view acts like a cropping image effect. Then i make 3 rectangles (imageRect, secRect and IntersectRect), the imageRect is the rect which show an image, secRect is rect which just act to darken whole imageRect, and the intersectRect is a rect which like an observe rect, what i want to do is like make a "hole" on secRect to see directly into imageRect (without the darken). here's my drawRect method :

- (void)drawRect:(NSRect)rect {
    // Drawing code here.
 NSImage *image = [NSImage imageNamed:@"Lonely_Tree_by_sican.jpg"];
 NSRect imageRect = [self bounds];

 [image compositeToPoint:NSZeroPoint operation:NSCompositeSourceOver ];

 if (NSIntersectsRect([myDrawRect currentRect], [self bounds])) {
  //get the intersectionRect
  intersectionRect = NSIntersectionRect([myDrawRect currentRect], imageRect);

  //draw the imageRect
  [image compositeToPoint:imageRect.origin operation:NSCompositeSourceOver];

  //draw the secRect and fill it with black and alpha 0.5
  NSRect secRect = NSMakeRect(imageRect.origin.x, imageRect.origin.y, imageRect.size.width, imageRect.size.height);
  [[NSColor colorWithCalibratedRed:0.0 green:0.0 blue:0.0 alpha:0.5] set];
  [NSBezierPath fillRect:secRect];

  //have no idea for the intersectRect
  /*[image compositeToPoint:intersectionRect.origin
        fromRect:secLayer
       operation:NSCompositeXOR
        fraction:1.0];*/

 }

 //draw the rectangle
 [myDrawRect beginDrawing];

}

I have my own class (myDrawRect) to draw a rectangle based on mouse click on [self bounds], so just ignore the beginDrawing command.

Any help would be fine, thanks. Hebbian.

A: 

You're doing far more work than you need to, and you're using deprecated methods (the compositeToPoint:operation: and compositeToPoint:fromRect:operation:fraction: methods) to do it.

All you need to do is send the image a single drawInRect:fromRect:operation:fraction: message. The fromRect: parameter is the rectangle you want to crop to; if you don't want to scale the cropped section, then the destination rect (the drawInRect: parameter) should have the same size.

About the only extra work you may need to do is if the image may be bigger than the view and you want to only draw the section that's within the view's bounds: When that happens, you'll need to inset the crop rectangle by the difference in size between the crop rectangle and the view bounds.

Peter Hosey