在Cocoa中以编程方式编辑图像?
我想为我的应用程序设置一个自定义鼠标光标,并希望通过编程将默认光标的颜色更改为自定义颜色,方法是用自定义颜色替换白色边框。问题是,我甚至不知道从哪里开始以编程方式编辑Cocoa中的图像,因此非常感谢您的帮助 您可以使用-[NSCursor arrowCursor]获取默认光标。一旦有了光标,就可以使用-[NSCursor image]获取其图像。您不应该修改其他对象的图像,因此应该复制该图像。然后,您应该编辑图像,并使用-[NSCursor initWithImage:hotSpot:]创建一个新光标。您的代码应该如下所示:在Cocoa中以编程方式编辑图像?,cocoa,image,cursor,Cocoa,Image,Cursor,我想为我的应用程序设置一个自定义鼠标光标,并希望通过编程将默认光标的颜色更改为自定义颜色,方法是用自定义颜色替换白色边框。问题是,我甚至不知道从哪里开始以编程方式编辑Cocoa中的图像,因此非常感谢您的帮助 您可以使用-[NSCursor arrowCursor]获取默认光标。一旦有了光标,就可以使用-[NSCursor image]获取其图像。您不应该修改其他对象的图像,因此应该复制该图像。然后,您应该编辑图像,并使用-[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一次绘制一个像素会非常慢,因此您只需这样做,就可以了解所有这些是如何工作的。我的最终代码。这将采用标准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];
}
非常感谢你的回答,我终于知道了如何给光标上色(见下面我的答案)。