cocos2d-lua 图片裁剪自定义形状

有两种方法一种是用clippingNode来进行遮罩--对节点进行遮罩式裁剪

--picPath and stencilPath 尺寸要一致, 更新节点需要移除之前的节点
function cc.exports.exchangeImageToClipNode(imgNode, picPath, stencilPath,index)
    imgNode:setVisible(false)
    local parent = imgNode:getParent()
    local clipnode = parent:getChildByName("ClipNode"..tostring(index))
    if clipnode then
        clipnode:removeFromParent()
    end

    local clipNodeEx = cc.ClippingNode:create()
    parent:addChild(clipNodeEx)
    local maskNode = imgNode:clone()
    maskNode:loadTexture(picPath, ccui.TextureResType.localType)
    maskNode:setVisible(true)
    local sprite = cc.Sprite:create(stencilPath)
    clipNodeEx:addChild(maskNode)
    clipNodeEx:setStencil(sprite)
    maskNode:setPosition(imgNode:getPosition())
    sprite:setPosition(imgNode:getPosition())
    clipNodeEx:setName("ClipNode"..tostring(index))
    clipNodeEx:setInverted(true)
    clipNodeEx:setAlphaThreshold(0.5)

    return clipNodeEx
end

另一种是用renderTexture进行裁剪

--对纹理进行裁剪  裁剪的图片路径spritePath   裁剪的形状图片路径maskPath
function cc.exports.maskedSprite(spritePath, maskPath)
    local textureSprite = cc.Sprite:create(spritePath)
    local textureSize = textureSprite:getContentSize()

    local maskSprite = cc.Sprite:create(maskPath)
    local maskSize = maskSprite:getContentSize()

    local renderTexture = cc.RenderTexture:create(maskSize.width,maskSize.height)
    maskSprite:setPosition(cc.p(maskSize.width/2,maskSize.height/2))
    textureSprite:setPosition(cc.p(textureSize.width/2,textureSize.height/2))

    maskSprite:setBlendFunc(cc.blendFunc(GL_ONE,GL_ZERO))
    textureSprite:setBlendFunc(cc.blendFunc(GL_DST_ALPHA,GL_ZERO))

    renderTexture:begin()
    maskSprite:visit()
    textureSprite:visit()
    renderTexture:endToLua()

    local retSprite = cc.Sprite:createWithTexture(renderTexture:getSprite():getTexture())
    retSprite:setFlippedY(true)
    return retSprite
end

第一种方法可以根据imageview的尺寸自适应,不过有个bug,如果有弹出窗的层级高于在遮罩图片的被创建前父节点的层级,当遮罩图片被创建以后,弹出窗也会被遮罩裁剪

第二种方法则是在利用需要裁剪的图片纹理,重新创建了一个裁剪图片,因此图片的大小是相对于纹理的尺寸,大小需要手动进行设置

你可能感兴趣的:(cocos2dx-lua)