文章出自于 http://blog.csdn.net/zhouyunxuan
网上很多2.X的像素检测,我就写个3.X能用的- -,留着以后可能用得着
主要功能判断点击的是否为图片的透明区域。
private:
RenderTexture* m_rt;
Sprite* sp;
Image* pImage;
auto s = Director::getInstance()->getWinSize();
auto sp = Sprite::create("QingLongZhan2.png");
sp->setPosition(s / 2);
addChild(sp);
Size size = sp->getContentSize();
m_rt = RenderTexture::create(size.width, size.height, Texture2D::PixelFormat::RGBA8888);
m_rt->ignoreAnchorPointForPosition(true);
m_rt->setPosition(sp->getPosition());
m_rt->setAnchorPoint(sp->getAnchorPoint());
addChild(m_rt, 0, 1);
Sprite* pTempSpr = Sprite::createWithSpriteFrame(sp->getSpriteFrame());
pTempSpr->setPosition(Vec2(pTempSpr->getContentSize().width / 2, pTempSpr->getContentSize().height / 2));
// 绘画开始
m_rt->begin();
// 绘制
pTempSpr->visit();
// 结束绘制
m_rt->end();
// 通过画布拿到这张画布上每个像素点的信息,封装到CCImage中
pImage = m_rt->newImage();
auto listen = EventListenerTouchOneByOne::create();
listen->setSwallowTouches(false);
listen->onTouchBegan = [&](Touch* touch, Event* event){
auto target = static_cast<Sprite*>(event->getCurrentTarget());
if(target->getBoundingBox().containsPoint(touch->getLocation()))
{
//获取像素数据
Color4B color4B;
Vec2 nodePos = target->convertTouchToNodeSpace(touch);
unsigned int x = nodePos.x;
unsigned int y = target->getContentSize().height - nodePos.y;
unsigned char* data_ = pImage->getData();
unsigned int *pixel = (unsigned int *)data_;
pixel = pixel + (y * (int)target->getContentSize().width) * 1 + x * 1;
//R通道
color4B.r = *pixel & 0xff;
//G通道
color4B.g = (*pixel >> 8) & 0xff;
//B通过
color4B.b = (*pixel >> 16) & 0xff;
//Alpha通道,我们有用的就是Alpha
color4B.a = (*pixel >> 24) & 0xff;
if(color4B.a == 0)
{
log("你点到人家透明的地方啦。");
}
}
return true;
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(listen, sp);