2010-08-24 36 views
0

我有一個顯示圖像的NSView,我想使這個視圖的行爲像一個裁剪圖像效果。然後,我製作了3個矩形(imageRect,secRectIntersectRect),imageRect是顯示圖像的矩形,secRect是矩形,它只是使整個圖像變暗,而intersectRect是一個矩形,它像一個觀察矩形,我想要的做就像在secRect上做個「洞」,直接看到imageRect(沒有變暗)。這裏是我的drawRect方法:使用NSImage操作產生作物效果

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

您正在做的工作比您需要的要多得多,您正在使用已棄用的方法(compositeToPoint:operation:compositeToPoint:fromRect:operation:fraction:方法)來完成此工作。

您只需發送圖像drawInRect:fromRect:operation:fraction: message即可。 fromRect:參數是要裁剪的矩形;如果您不想縮放裁剪區域,則目標矩形(參數drawInRect:)應具有相同的大小。

關於你可能需要做的唯一的額外工作是如果圖像可能比視圖大,你想只繪製視圖的範圍內是這樣的部分:當發生這種情況,你需要inset作物矩形由裁剪矩形和視圖邊界之間的大小差異決定。