场景
-
在开发
Cocoa
程序时, 往往需要在禁用按钮时实现一些灰度的特效, 和Windows
一样, 如何实现呢? -
NSImage
有没有相关的方法呢?NSImage
有一个颜色空间colorSpace
的概念, 能通过转换为灰度实现吗?
说明
- 试用灰度空间(不行), 通过
NSImage
的方法representations
获取到NSBitmapImageRep
,之后在通过bitmapImageRepByConvertingToColorSpace
方法转换为新的ImageRep
, 可惜报错.
NSBitmapImageRep *targetImageRep = [sourceImageRep bitmapImageRepByConvertingToColorSpace:targetColorSpace
renderingIntent:NSColorRenderingIntentPerceptual];
return targetImageRep;
<Error>: The function `CGContextClear' is obsolete and will be removed in an upcoming update. Unfortunately, this application, or a library it uses, is using this obsolete function, and is thereby contributing to an overall degradation of system performance.
- 通过改变图片的像素值为灰度值达到目的, 只是这种方式效率比较低.
+ (NSImage*)convertToGray:(NSImage*)image
{
NSAutoreleasePool* pool = [NSAutoreleasePool new];
NSBitmapImageRep* imageRep = [NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]];
for(int y = 0; y < image.size.height; ++y) {
for(int x = 0; x < image.size.width; ++x) {
NSColor* color = [imageRep colorAtX:x y:y];
if([color redComponent] != 1){
[imageRep setColor:[NSColor colorWithDeviceRed:127/255.0 green:127/255.0 blue:127/255.0 alpha:0.2] atX:x y:y];
}
}
}
NSImage* targetImage = [[NSImage alloc] initWithSize:image.size];
[targetImage addRepresentation:imageRep];
[pool drain];
return targetImage;
}
- 更好的方式?请留言
参考
NSBitmapImageRep.bitmapImageRepByConvertingToColorSpace calling deprecated CGContextClear