使用 NSImage 操作制作裁剪效果

Heb*_*ian 1 cocoa objective-c nsimage

我有一个显示图像的 NSView,我想让这个视图像裁剪图像效果一样。然后,我让3个矩形(imageRectsecRectIntersectRect)时,imageRect是显示图像的矩形,secRect是矩形这只是充当变暗整体imageRect,并且intersectRect是像一个观察的rect一个矩形,我想要做的是什么样的做一个“洞” 就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];

}
Run Code Online (Sandbox Code Playgroud)

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

任何帮助都会很好,谢谢。赫比。

Pet*_*sey 5

您正在做的工作比您需要的要多得多,并且您正在使用不推荐使用的方法(compositeToPoint:operation:compositeToPoint:fromRect:operation:fraction:方法)来完成它。

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

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