1

我有一个显示图像的 NSView,我想让这个视图像裁剪图像效果一样。然后我制作3个矩形(imageRectsecRectIntersectRect),imageRect是显示图像secRect的矩形,只是使整体变暗的矩形imageRect,并且intersectRect是像观察矩形一样的矩形,我想做的是制作一个“洞" 上secRect直接看到imageRect(没有变暗)。这是我的 drawRect 方法:

- (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];

}

我有自己的类(myDrawRect)来根据鼠标点击绘制一个矩形[self bounds],所以只需忽略该beginDrawing命令。

任何帮助都可以,谢谢。赫比。

4

1 回答 1

5

您所做的工作远远超出了您的需要,并且您正在使用已弃用的方法(thecompositeToPoint:operation:compositeToPoint:fromRect:operation:fraction:方法)来完成它。

您需要做的就是向图像发送一条drawInRect:fromRect:operation:fraction:消息fromRect:参数是要裁剪到的矩形;如果您不想缩放裁剪部分,则目标矩形(drawInRect:参数)应该具有相同的大小。

您可能需要做的唯一额外工作是,如果图像可能比视图大,并且您只想绘制视图边界内的部分:发生这种情况时,您需要插入裁剪矩形的差异裁剪矩形和视图边界之间的大小。

于 2010-08-25T05:21:25.687 回答