如何在Cocos2D 1.0 中掩饰一个精灵(六)

来源:互联网 发布:java实现身份证的验证 编辑:程序博客网 时间:2024/05/15 07:50

大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处.
如果觉得写的不好请告诉我,如果觉得不错请多多支持点赞.谢谢! hopy ;)


掩饰一个精灵:实现代码

打开HelloWorldLayer.m并且在init方法上方添加如下方法:

- (CCSprite *)maskedSpriteWithSprite:(CCSprite *)textureSprite maskSprite:(CCSprite *)maskSprite {     // 1    CCRenderTexture * rt = [CCRenderTexture renderTextureWithWidth:maskSprite.contentSizeInPixels.width height:maskSprite.contentSizeInPixels.height];    // 2    maskSprite.position = ccp(maskSprite.contentSize.width/2, maskSprite.contentSize.height/2);    textureSprite.position = ccp(textureSprite.contentSize.width/2, textureSprite.contentSize.height/2);    // 3    [maskSprite setBlendFunc:(ccBlendFunc){GL_ONE, GL_ZERO}];    [textureSprite setBlendFunc:(ccBlendFunc){GL_DST_ALPHA, GL_ZERO}];    // 4    [rt begin];    [maskSprite visit];            [textureSprite visit];        [rt end];    // 5    CCSprite *retval = [CCSprite spriteWithTexture:rt.sprite.texture];    retval.flipY = YES;    return retval;}

让我们一段一段的看:

  1. 用和掩饰精灵相同的宽和高创建CCRenderTexture.
  2. 将掩饰精灵和纹理精灵放置到左下0,0的位置.
  3. 为之前描述的每一个精灵设置混合函数.
  4. 调用begin去在CCRenderTexture中开始绘制,绘制掩饰图片然后是纹理,最后调用end去结束绘制.
  5. 基于CCRenderTexture的精灵纹理创建一个新的精灵,因为该纹理是上下翻转的,所以需要在y坐标轴上翻转它.

在我们讨论的所有东西之后,现在让我们来实际使用它!用一下代码替换BEGINTEMP和ENDTEMP之间的代码:

CCSprite * mask = [CCSprite spriteWithFile:@"CalendarMask.png"];        CCSprite * maskedCal = [self maskedSpriteWithSprite:cal maskSprite:mask];maskedCal.position = ccp(winSize.width/2, winSize.height/2);[self addChild:maskedCal];

该代码用我们新的函数去掩饰日历精灵,并且添加掩饰后的版本到场景中.

编译运行,你应该看到一个被Cocos2D 1.0掩饰后的精灵!

这里写图片描述

关于CCRenderTexture方法的缺点

对于这个简单的例子app来说工作的不错,但是这里该方法有一些缺点你可能会在更复杂的app中注意到:

  • 每一次你应用一个掩饰图片都会在内存中创建额外的纹理.纹理内存在iPhone中是非常受限制的,所以你必须非常小心对待你一次可以添加多少纹理到内存中去.如果一次添加少量纹理那表示没什么问题,但是如果你必须掩饰100张图片呢?
  • 绘制会耗费时间.用CCRenderTexture绘制并非毫无代价(特别是你的纹理尺寸变大的时候).如果你频繁的做这些事,你可能注意到性能上的冲击.

就像我前面提到的那样,在OpenGL ES 1.0中据我所知没有办法绕过这些缺点.但在OpenGL ES 2.0中你可以通过着色器掩饰的更有效率 — 但是那是另一段旅程的主题了! ;)

0 0