好了这里我先上代码
首先定义这个函数
void HelloWorld::changeDatas(Image *image,Image * image1,Point point) { auto data = image->getData();//橡皮擦数据头指针 auto data1 = image1->getData();//被擦除数据头指针 auto size = Director::getInstance()->getVisibleSize(); int pha = 3; if (image->hasAlpha())//判断是否有Alpha通道 { pha = 4; } for (int x = 0; x < image->getWidth(); ++x) { for (int y = 0; y < image->getHeight(); ++y) { /*下面是获取rgb颜色值 这里说明一下 data是指向数据的头指;指针指向数据的排列方式是 data 0~3 rgba data 4~7 rgba 所以没有Alpha通道 的排列方式是 data 0~2 rgb data 3~5 rgb */ unsigned char *pixel = data + (x + y * image->getWidth()) * pha;//遍历每个像素点的rgb unsigned int r = (unsigned int)*pixel; unsigned int g = (unsigned int)*(pixel + 1); unsigned int b = (unsigned int)*(pixel + 2); unsigned int a = (unsigned int)*(pixel + 3); if (r != 0 || g != 0 || b != 0 || a != 0)//如果该点有颜色就将被剪裁区域的颜色替换成无色 { Point changep = Point(size.width/2,size.height-size.height/2);//因为Opengl的坐标在左上角所以做坐标转换;这里应该把被剪裁区域的图坐标转换成OPENGL Point changep1 = Point(changep.x - image1->getWidth() / 2,changep.y - image1->getHeight() / 2); int c = x + point.x - changep1.x - image->getWidth() / 2; int d = y + point.y - changep1.y - image->getHeight() / 2; if (c>0&&d>0&&c < image1->getWidth() && d <image1->getHeight()) { int pha1 = 3; if (image1->hasAlpha()) { pha1 = 4; } unsigned char *pixel1 = data1 + (c + d * image1->getWidth()) * pha1; *pixel1 = 0;//数据修改 *(pixel1 + 1) = 0; *(pixel1 + 2) = 0; } } } } }
然后在初始化方法里
auto CliperImage = new Image();//创建一个需要剪裁的Image CliperImage->initWithImageFile("HelloWorld.png"); auto image = new Image();//创建一个橡皮擦Image image->initWithImageFile("123.png"); auto text = new Texture2D(); text->initWithImage(CliperImage); auto sp = Sprite::createWithTexture(text); sp->setPosition(visibleSize.width/2,visibleSize.height/2); this->addChild(sp,33);//通过不停的更新这个SP来实现涂擦效果 也可以认为更新了CliperImage的DATA来实现 /*创建监听事件*/ auto linstener = EventListenerTouchOneByOne::create(); linstener->onTouchBegan = [this](Touch *touch,Event *event) { return true; }; linstener->onTouchMoved = [this,CliperImage,image](Touch *touch,Event *event) { auto size = Director::getInstance()->getVisibleSize(); this->removeChildByTag(33); changeDatas(image,Point(touch->getLocation().x,size.height - touch->getLocation().y)); auto text1 = new Texture2D(); text1->initWithImage(CliperImage); auto sp = Sprite::createWithTexture(text1); sp->setPosition(size.width / 2,size.height / 2); addChild(sp,33); }; linstener->onTouchEnded = [this,Event *event) { auto size = Director::getInstance()->getVisibleSize(); this->removeChildByTag(33); changeDatas(image,size.height - touch->getLocation().y)); auto text1 = new Texture2D(); text1->initWithImage(CliperImage); auto sp = Sprite::createWithTexture(text1); sp->setPosition(size.width/2,size.height/2); addChild(sp,33); }; _eventDispatcher->addEventListenerWithSceneGraPHPriority(linstener,this);
好了我们来看下效果同样的123.png是这个
效果图