2011-03-19 58 views
0

我想爲我的應用程序設置一個自定義鼠標光標,並且希望通過用自定義顏色替換白色邊框來以編程方式將默認光標的顏色更改爲自定義顏色。問題是,我甚至不知道從哪裏開始以編程方式編輯Cocoa中的圖像,所以任何幫助都是值得讚賞的!以編程方式編輯Cocoa中的圖像?

回答

0

我的最終代碼。這將採用標準IBeam光標(當您將鼠標懸停在文本視圖上時),並將指針中的彩色光標存儲在coloredIBeamCursor指針中。

- (void)setPointerColor:(NSColor *)newColor { 
    // create the new cursor image 
    [[NSGraphicsContext currentContext] CIContext]; 
    // create the layer with the same color as the text 
    CIFilter *backgroundGenerator=[CIFilter filterWithName:@"CIConstantColorGenerator"]; 
    CIColor *color=[[[CIColor alloc] initWithColor:newColor] autorelease]; 
    [backgroundGenerator setValue:color forKey:@"inputColor"]; 
    CIImage *backgroundImage=[backgroundGenerator valueForKey:@"outputImage"]; 
    // create the cursor image 
    CIImage *cursor=[CIImage imageWithData:[[[NSCursor IBeamCursor] image] TIFFRepresentation]]; 
    CIFilter *filter=[CIFilter filterWithName:@"CIColorInvert"]; 
    [filter setValue:cursor forKey:@"inputImage"]; 
    CIImage *outputImage=[filter valueForKey:@"outputImage"]; 
    // apply a multiply filter 
    filter=[CIFilter filterWithName:@"CIMultiplyCompositing"]; 
    [filter setValue:backgroundImage forKey:@"inputImage"]; 
    [filter setValue:outputImage forKey:@"inputBackgroundImage"]; 
    outputImage=[filter valueForKey:@"outputImage"]; 
    // get the NSImage from the CIImage 
    NSCIImageRep *rep=[NSCIImageRep imageRepWithCIImage:outputImage]; 
    NSImage *newImage=[[[NSImage alloc] initWithSize:[outputImage extent].size] autorelease]; 
    [newImage addRepresentation:rep]; 
    // remove the old cursor (if any) 
    if (coloredIBeamCursor!=nil) { 
     [self removeCursorRect:[self visibleRect] cursor:coloredIBeamCursor]; 
     [coloredIBeamCursor release]; 
    } 
    // set the new cursor 
    NSCursor *coloredIBeamCursor=[[NSCursor alloc] initWithImage:newImage hotSpot:[[NSCursor IBeamCursor] hotSpot]]; 
    [self resetCursorRects]; 
} 
0

您可以使用 - [NSCursor arrowCursor]獲取默認光標。一旦你有了遊標,你就可以用 - [NSCursor圖像]獲得它的圖像。你不應該修改另一個對象的圖像,所以你應該複製該圖像。然後你應該編輯圖像,並用 - [NSCursor initWithImage:hotSpot:]創建一個新的遊標。你的代碼應該是這個樣子:

- (NSImage *)customArrowCursorImage { 
    NSImage *image = [[[NSCursor arrowCursor] image] copy]; 
    [image lockFocus]; 
    /// Do custom drawing 
    [image unlockFocus]; 
} 

- (NSCursor *)customArrowCursor { 
    NSImage *image = [self customArrowCursorImage]; 
    NSPoint hotSpot = [[NSCursor arrowCursor] hotSpot]; 
    return [[[NSCursor alloc] initWithImage:image hotSpot:hotSpot] autorelease]; 
} 

您應該能夠使用的核心圖像過濾器更換白色具有自定義圖像的顏色。但是,如果您只想開始使用,可以使用NSReadPixel()和NSRectFill一次爲一個像素着色。使用NSReadPixel和NSRectFill一次繪製一個像素的時間會非常慢,所以您只應該這樣做以瞭解所有這些工作方式。

+0

非常感謝你的回答,我終於知道了如何爲光標着色(請參閱下面的答案)。 – Nickkk 2011-06-25 10:15:03