cocos2d-x 3.1.1 学习笔记[20] 像素级触摸处理



文章出自于  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);










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值