0

我必须在此处找到 CIRadialGradient 的 Apples Doc 中生成的图像:

CI径向渐变

我尝试了很多方法并以:

+(NSImage*)radialGradientWithR0:(float)r0 r1:(float)r1 c0:(NSColor*)c0 c1:(NSColor*)c1 imageDimensionPx:(int)imageDimension
{
    CIColor* cc0 = [[CIColor alloc]initWithColor:c0];
    CIColor* cc1 = [[CIColor alloc]initWithColor:c1];
    CIVector* civ = [CIVector vectorWithX:imageDimension/2 Y:imageDimension/2];

    CIFilter* filter = [CIFilter filterWithName:@"CIRadialGradient"];
    [filter setDefaults];
    [filter setValue:civ forKey:@"inputCenter"];
    [filter setValue:[NSNumber numberWithFloat:r0] forKey:@"inputRadius0"];
    [filter setValue:[NSNumber numberWithFloat:r0] forKey:@"inputRadius1"];
    [filter setValue:cc0 forKey:@"inputColor0"];
    [filter setValue:cc1 forKey:@"inputColor1"];

    CIImage* outputImage = [filter valueForKey:@"outputImage"];

    NSRect outputImageRect = NSRectFromCGRect([outputImage extent]);
    NSImage* blurredImage = [[NSImage alloc]
                             initWithSize:NSMakeSize(imageDimension,  imageDimension)];

    [blurredImage lockFocus];
    [blurredImage drawAtPoint:NSZeroPoint fromRect:NSMakeRect(0, 0, imageDimension, imageDimension) operation:NSCompositeSourceOver fraction:1.0];
    [blurredImage unlockFocus];

    return blurredImage;
}

但我能得到的只是一个空图像。

请帮我。

谢谢

菲利克斯

4

1 回答 1

2

您的代码中有几个错误会阻止它工作:

  • 参数中的错字:第二次调用中未使用 r1

您需要更改第二行:

 [filter setValue:[NSNumber numberWithFloat:r0] forKey:@"inputRadius0"];
 [filter setValue:[NSNumber numberWithFloat:r0] forKey:@"inputRadius1"];
  • 你不需要这个:NSRect outputImageRect = NSRectFromCGRect([outputImage extent]);

  • [blurredImage lockFocus];其次[blurredImage drawAtPoint:基本上意味着类似:绘制图像本身。你的意思是:[outputImage drawAtPoint:..]

这是一种可以满足您要求的方法:

-(NSImage *) radialGradientWithR0:(float)r0 r1:(float)r1 c0:(NSColor*)c0 c1:(NSColor*)c1 imageDimensionPx:(int)imageDimension {

    CIColor* cc0 = [[CIColor alloc]initWithColor:c0];
    CIColor* cc1 = [[CIColor alloc]initWithColor:c1];
    CIVector* civ = [CIVector vectorWithX:imageDimension/2 Y:imageDimension/2];

    CIFilter* filter = [CIFilter filterWithName:@"CIRadialGradient"];

    [filter setValue:civ forKey:@"inputCenter"];
    [filter setValue:[NSNumber numberWithFloat:r0] forKey:@"inputRadius0"];
    [filter setValue:[NSNumber numberWithFloat:r1] forKey:@"inputRadius1"];
    [filter setValue:cc0 forKey:@"inputColor0"];
    [filter setValue:cc1 forKey:@"inputColor1"];

    NSImage * res = [[NSImage alloc] initWithSize:NSMakeSize(imageDimension, imageDimension)];
    [res lockFocus];
    [[filter valueForKey:@"outputImage"]
     drawAtPoint:NSZeroPoint 
     fromRect:NSMakeRect(0, 0, imageDimension, imageDimension)                   
     operation:NSCompositeDestinationAtop  fraction:1.0];
    [res unlockFocus];
    return res;
}

显示径向渐变的 NSImageWell

于 2013-04-02T14:33:58.533 回答