0

我正在尝试使用 CIFilter 生成一个条带,然后从中创建一个 SKTexture。这是我的代码。

      CIFilter *filter = [CIFilter filterWithName:@"CIStripesGenerator"];
    [filter setDefaults];
    [filter setValue:[CIColor colorWithRed:1 green:1 blue:1] forKey:@"inputColor0"];
    [filter setValue:[CIColor colorWithRed:0 green:0 blue:0] forKey:@"inputColor1"];

   //updated the code, whith this line   
   //stil the same problem
    CIImage *croppedImage = [filter.outputImage imageByCroppingToRect:CGRectMake(0, 0, 320, 480)];

    SKTexture *lightTexture = [SKTexture textureWithImage:[UIImage imageWithCIImage:croppedImage]];

    SKSpriteNode *light = [SKSpriteNode spriteNodeWithTexture:lightTexture size:self.size];

但是,我在最后一行收到一个运行时错误,任何帮助都将不胜感激,除了 (lldb),编译器没有给出更多解释。

更新:感谢rickster指导我找到解决方案

-(UIImage*) generateImage {
// 1
CIContext *context = [CIContext contextWithOptions:nil];
CIFilter *filter = [CIFilter filterWithName:@"CIStripesGenerator"];
[filter setDefaults];
[filter setValue:[CIColor colorWithRed:1 green:1 blue:1] forKey:@"inputColor0"];
[filter setValue:[CIColor colorWithRed:0 green:0 blue:0] forKey:@"inputColor1"];
// 2
CGImageRef cgimg =
[context createCGImage:filter.outputImage fromRect:CGRectMake(0, 0, 320, 480)];
// 3
UIImage *newImage = [UIImage imageWithCGImage:cgimg];
// 4
CGImageRelease(cgimg);
return newImage;
 }

然后,我可以从图像创建纹理:

    SKTexture *stripesTexture = [SKTexture textureWithImage:[self generateImage]];

    SKSpriteNode *stripes = [SKSpriteNode spriteNodeWithTexture:stripesTexture];
    stripes.position=CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
    [self addChild: stripes];
4

1 回答 1

1

这里有几个问题:

  1. 您没有用于渲染图像的核心图像上下文。创建一个:

    CIContext *context = [CIContext contextWithOptions:nil];
    

    这可能不会提供实时渲染性能。但看起来您只想要一次性生成静态纹理,所以没关系。

  2. 大多数生成器过滤器产生无限范围的图像。您需要将裁剪过滤器添加到过滤器链中,或者使用可让您指定所需图像的矩形的方法来渲染图像,例如createCGImage:fromRect:. 然后SKTexture从生成的CGImageRef.

于 2014-03-22T16:15:45.763 回答