先說一點,這是從別人那裏扒來的,親測有效以爲不錯,分享一下:xcode
原理很簡單,就是判斷按鈕圖片的點擊區域 像素點透明度是否是0,須要修改源代碼;ide
我拿cocos2dx 3.10的版本(xcode環境)舉例:函數
第一步,新建一個cocos項目,找到cocos的源代碼中的Widget,它在ui 》base 》UIWidget.h文件中,在Widget類的public中添加三個函數:測試
virtual bool AlphaTouchCheck(const Vec2 &point);ui
virtual bool getAlphaTouchEnable();this
virtual void setAlphaTouchEnable(bool isAlphaTouch);spa
而後再添加一個布爾型變量:code
bool _isAlphaTouchEnable;orm
在UIWidget.cpp文件中實現:圖片
bool Widget::AlphaTouchCheck(const Vec2 &point)
{
returntrue;
}
bool Widget::getAlphaTouchEnable()
{
return_isAlphaTouchEnable;
}
void Widget::setAlphaTouchEnable(bool isAlphaTouch)
{
_isAlphaTouchEnable = isAlphaTouch;
}
第二步,找到Button的源代碼,在ui 》widgets 》UIButton.h中重載函數bool AlphaTouchCheck(constVec2& point); 在UIbutton.cpp中實現:
bool Button::AlphaTouchCheck(const Vec2& point)
{
if (getAlphaTouchEnable())
{
Image* normalImage =newImage();
normalImage->initWithImageFile(_normalFileName);//_normalFileName是button默認的那張圖片路徑
auto data = normalImage->getData();
if (data ==NULL)
{
returntrue;
}
auto locationInNode =this->convertToNodeSpace(point);
int pa =4 * ((normalImage->getHeight() - (int)(locationInNode.y) -1) * normalImage->getWidth() + (int)(locationInNode.x)) +3;
unsignedint ap = data[pa];
if (ap <20)//這裏判斷透明度,小於20就判斷爲點擊無效,課根據本身的須要修改成0等等..
{
CC_SAFE_DELETE(normalImage);
returnfalse;
}
else
{
CC_SAFE_DELETE(normalImage);
returntrue;
}
}
returntrue;
}
第三步:比較重要,在在ui 》base 》UIWidget.cpp文件中找到boolWidget::onTouchBegan(Touch *touch,Event*unusedEvent),在
_touchBeganPosition = touch->getLocation();這一句代碼後面添加
if(!AlphaTouchCheck(_touchBeganPosition))
{
return false;
}
ok,完成。源代碼修改到這裏結束;
而後基本沒什麼,就是Button的正常使用,要注意一點的是,這個button的點擊效果有個開關:setAlphaTouchEnable(bool );
測試在HelloWorld.cpp中添加一個Button,選一個不規則的圖片做爲默認按鈕圖,代碼:
Button*s = Button::create("testbtn.png");//圖片中間區域透明
s->addTouchEventListener(this,toucheventselector(HelloWorld::btnclick));
s->setPosition(Vec2(300,200));
addChild(s);
s->setAlphaTouchEnable(true);//false爲關閉該功能,和普通button同樣,點擊中間區域按鈕後執行btnclick;true爲開啓,點擊中間區域後不進入btnclick函數;
voidHelloWorld::btnclick(Ref*r,cocos2d::ui::TouchEventType t)
{
CCLog("Log:%s" ,"click!");
}
附加是我測試使用的圖片,中間是空的