quick cocos CCClippingNode实现圆角图片 + 修改父parent,setParent的用法

本文介绍如何在Cocos2d-x中通过setParent等方法复用子节点,减少内存消耗,并提供了一个实现圆角图片的具体实例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

quick cocos设置父parent,setParent的用法

我们在使用cocos的时候,有的时候需要把子node(当然包含所有继承自node 的组件)从父node中移除,方便复用,减少内存,cpu的开销。好了,废话不多说,直接上代码:

    nodeChildren:getParent():getChildren():removeObject(nodeChildren,false);
    nodeChildren:setParent(nil);
    nodeChildren:setTag(1)
    nodeChildren:setPosition(ccp(0,0))
    nodeNew:addChild(nodeChildren);

上面是实现圆角图片的基础,复用图片剪切圆角,不说了直接贴代码

--imgP=原始图片 pw=图片宽 py=图片高 tagImg=原来的图片tag(检查重复用)
function getRoundImg(imgP,pw,py,tagImg)
    if imgP == nil or tolua.isnull(imgP) then return end
    tagImg = tagImg or 0
    if imgP:getParent():getTag() == tagImg+100 then
        cclog("getRoundImg have already add clippnode") --防止重复添加导致创建了多个clippnode
        return imgP
    end
    pw = pw or 200
    py = py or 200
    local px,py=imgP:getPositionX(),imgP:getPositionY()
    local pa = imgP:getAnchorPoint()
    local pw,ph = imgP:getContentSize().width * imgP:getScaleX(),imgP:getContentSize().height * imgP:getScaleY()

    local stencil = CCSprite:create()
    local spriteFrameCache = CCSpriteFrameCache:sharedSpriteFrameCache()
    spriteFrameCache:addSpriteFramesWithFile('res/圆角图片的.plist')
    local rBg = spriteFrameCache:spriteFrameByName("圆角图片名.png")
    stencil:setDisplayFrame(rBg)
    stencil:setAnchorPoint(pa)
    stencil:setScaleX(pw/200)
    stencil:setScaleY(pw/200)

    local clipNode = CCClippingNode:create()
    clipNode:setStencil(stencil)
    clipNode:setInverted(false)
    clipNode:setAlphaThreshold(0.05)
    clipNode:setAnchorPoint(pa)
    clipNode:setPosition(ccp(px,py))
    clipNode:setTag(imgP:getTag()+100)

    imgP:getParent():addChild(clipNode)

    imgP:getParent():getChildren():removeObject(imgP,false);
    imgP:setParent(nil);
    imgP:setTag(1)
    imgP:setPosition(ccp(0,0))
    clipNode:addChild(imgP);

    return imgP
end

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值