如何解决在可可中以编程方式编辑图像?
| 我想为我的应用设置自定义鼠标光标,并希望通过将白色边框替换为自定义颜色,以编程方式将默认光标的颜色更改为自定义颜色。问题是我什至不知道从哪里开始以编程方式在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光标(将光标悬停在textview上的光标)并将彩色的光标存储在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];
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。