RenderTexture动态创建纹理

CCRenderTexture,它允许你来动态创建纹理,并且可以在游戏中重用这些纹理。

  使用 CCRenderTexture非常简单 – 你只需要做以下5步就行了:

  1. 创建一个新的CCRenderTexture. 这里,你可以指定将要创建的纹理的宽度和高度。.
  2. 调用 CCRenderTexture:begin. 这个方法会启动OpenGL,并且接下来,任何绘图的命令都会渲染到CCRenderTexture里面去,而不是画到屏幕上。
  3. 绘制纹理. 你可以使用原始的OpenGL调用来绘图,或者你也可以使用cocos2d对象里面已经定义好的visit方法。(这个visit方法就会调用一些opengl命令来绘制cocos2d对象)
  4. 调用 CCRenderTexture:end. 这个方法会渲染纹理,并且会关闭渲染至CCRenderTexture的通道。
  5. 从生成的纹理中创建一个sprite. 你现在可以用CCRenderTexture的sprite.texture属性来轻松创建新的精灵了。
class RenderTextureSave : public RenderTextureTest
{
public:
    RenderTextureSave();
    ~RenderTextureSave();
    virtual std::string title();
    virtual std::string subtitle();
    virtual void onTouchesMoved(const std::vector<Touch*>& touches, Event* event);
    void clearImage(Object *pSender);
    void saveImage(Object *pSender);

private:
    RenderTexture *_target;
    Sprite *_brush;
};
void RenderTextureSave::onTouchesMoved(const std::vector<Touch*>& touches, Event* event)
{
    auto touch = touches[0];
    auto start = touch->getLocation();
    auto end = touch->getPreviousLocation();

    // begin drawing to the render texture
    _target->begin();

    // for extra points, we'll draw this smoothly from the last position and vary the sprite's
    // scale/rotation/offset
    float distance = start.getDistance(end);
    if (distance > 1)
    {
        int d = (int)distance;
        for (int i = 0; i < d; i++)
        {
            float difx = end.x - start.x;
            float dify = end.y - start.y;
            float delta = (float)i / distance;
            _brush->setPosition(Point(start.x + (difx * delta), start.y + (dify * delta)));
            _brush->setRotation(rand() % 360);
            float r = (float)(rand() % 50 / 50.f) + 0.25f;
            _brush->setScale(r);
            /*_brush->setColor(Color3B(CCRANDOM_0_1() * 127 + 128, 255, 255));*/
            // Use CCRANDOM_0_1() will cause error when loading libtests.so on android, I don't know why.
            _brush->setColor(Color3B(rand() % 127 + 128, 255, 255));
            // Call visit to draw the brush, don't call draw..
            _brush->visit();
        }
    }

    // finish drawing and return context back to the screen
    _target->end();
}
void RenderTextureSave::saveImage(cocos2d::Object *sender)
{
    static int counter = 0;

    char png[20];
    sprintf(png, "image-%d.png", counter);
    char jpg[20];
    sprintf(jpg, "image-%d.jpg", counter);

    _target->saveToFile(png, Image::Format::PNG);
    _target->saveToFile(jpg, Image::Format::JPG);
    

    auto image = _target->newImage();

    auto tex = TextureCache::getInstance()->addImage(image, png);

    CC_SAFE_DELETE(image);

    auto sprite = Sprite::createWithTexture(tex);

    sprite->setScale(0.3f);
    addChild(sprite);
    sprite->setPosition(Point(40, 40));
    sprite->setRotation(counter * 3);

    CCLOG("Image saved %s and %s", png, jpg);

    counter++;
}

 

你可能感兴趣的:(text)