loved2d按指定颜色剔除背景

-- SDL2风格的颜色剔除函数
function setColorKey(imagePath, colorKey, threshold)
    -- 加载ImageData(类似SDL_Surface)
    local imageData = love.image.newImageData(imagePath)
    local width, height = imageData:getDimensions()
    
    -- 将颜色值转换为0-1范围(如果传入的是0-255)
    local r, g, b
    if colorKey.r and colorKey.g and colorKey.b then
        r, g, b = colorKey.r/255, colorKey.g/255, colorKey.b/255
    else
        r, g, b = colorKey[1] or 0, colorKey[2] or 0, colorKey[3] or 0
    end
    
    threshold = threshold or 0
    
    -- 遍历所有像素(类似SDL_SetColorKey的底层操作)
    for y = 0, height - 1 do
        for x = 0, width - 1 do
            local pr, pg, pb, pa = imageData:getPixel(x, y)
            
            -- 计算颜色差异(欧几里得距离)
            local distance = math.sqrt(
                (pr - r)^2 + (pg - g)^2 + (pb - b)^2
            )
            
            -- 如果颜色匹配(在阈值内),设为透明
            -- SDL2的SDL_SetColorKey是精确匹配,这里加了阈值更灵活
            if distance <= threshold then
                imageData:setPixel(x, y, pr, pg, pb, 0)
            end
        end
    end
    
    -- 创建带透明色的图像(类似SDL_Texture)
    local image = love.graphics.newImage(imageData)
    image:setFilter("nearest", "nearest")
    
    return image
end

 

posted on 2026-01-26 17:15  小沙盒工作室  阅读(1)  评论(0)    收藏  举报