cocos2D lua 通过url获取微信头像

1.用户进入时,调用 downHeadByUrl(url,userID) 下载头像

url为头像链接地址,userID为用户唯一标识

2.刷新头像时,调用getUserFaceImage(userID) 获取图片纹理

可以用该纹理创建头像
local Image = getUserFaceImage(userID)
local headSp = cc.Sprite:createWithTexture(Image)

3.加载排行榜时,调用createHeadSprite(url,userID)创建头像精灵

创建一个头像精灵,链接不为空下载头像,下载完后更新头像纹理
//单独调用
function createHeadSprite(url,userID)
	local sp = cc.Sprite:create("任意头像图片.png")
	
	local function updateHeadImage(userID)
		local headImage = getUserFaceImage(userID)
		if headImage  ~= nil then
			sp:setTexture(headImage)
		end
	end
	
	if url ~= nil and string.len(url) > 0 then
		downHeadByUrl(url,userID,updateHeadImage)
	end
end
// 下载头像
function downHeadByUrl(url,userID)
	if url == nil then
		return
	end
	//存储名字
	local headPicName = userID..".png"
	local targetPlatform = cc.Application:getInstance():getTargetPlatform()
	//存储路径
	local filepath = cc.FileUtils:getInstance():getWritablePath()
	//windows下新增一个文件夹方便自己看
	if cc.PLATFORM_OS_WINDOWS == targetPlatform then
		filepath = filepath.."UserFaceImage"
		//ios执行不了这句  我也不知道为啥 
		os.execute("mkdir " .. filepath)
	end
	//下载的头像图片
	local imgFile = filepath.."/"..strName
	local xhr = cc.XMLHttpRequest:new()
	xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_ARRAY_BUFFER
	xhr:open("GET",requestUrl)
 
	local function OnDownLoadFinish()
		if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then
			local fileData = xhr.response
			local size = table.getn(fileData)
			if size > 100 then
				os.remove(imgFile)
				local file = io.open(imgFile,"wb+")
				for i = 1,size do
					file:write(string.char(fileData[i]))
				end
				file:close()
				if func ~= nil then
					func(true,userID)
				end
			else
				if func ~= nil then
					func(false,userID)
				end            
			end
		else
			if func ~= nil then
				func(false,userID)
			end
			xhr:unregisterScriptHandler()
		end
	end
	xhr:registerScriptHandler(OnDownLoadFinish)
	xhr:send()
end
// 获取头像纹理
function getUserFaceImage(userID)
	local filepath = cc.FileUtils:getInstance():getWritablePath()
	local targetPlatform = cc.Application:getInstance():getTargetPlatform()
	if cc.PLATFORM_OS_WINDOWS == targetPlatform then
		filepath = filepath.."UserFaceImage/"
	end
	local strName = userID..".png"
	local szImageName = filepath..strName
	//头像是否存在
	if fileExist(szImageName ) == true then
		local pTemp = cc.Sprite:create(szImageName)
		if pTemp ~= nil then
			return pTemp:getTexture()
		end
	else
		local pTemp = cc.Sprite:create("任意头像图片.png")
		if pTemp  ~= nil then
			return pTemp:getTexture()
		end
	end
end
//判断文件是否存在
function fileExist(path)
    if path == nil then
        return false
    end

    local file = io.open(path,"rb")
    if file ~= nil then
        file:close()
        return true
    end

    return false
end

= =第一次写 有什么问题和建议 你说吧,我听着,改不改看我心情~
QAQ我也不知道为啥我的代码对不齐。。。。


版权声明:本文为u012233081原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。