CameraShotHelper.lua.txt 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. local CameraShotHelper = {}
  2. function CameraShotHelper:SaveShotImage(tBytes, szImageName)
  3. local szPath = require("Base/Utils.lua"):TimeMonthFormat()
  4. local szFileDirectory = CS.UnityEngine.Application.dataPath .. "/" .. szPath
  5. if not CS.System.IO.Directory.Exists(szFileDirectory) then
  6. CS.System.IO.Directory.CreateDirectory(szFileDirectory)
  7. end
  8. local szFilePath = szFileDirectory .. "/" ..szImageName .. ".png"
  9. CS.System.IO.File.WriteAllBytes(szFilePath, tBytes)
  10. end
  11. local function GetShotImage(cameraObj, nWidth, nHeight)
  12. local cameraComponent = cameraObj.transform:GetComponent("Camera")
  13. local renderTexture = CS.UnityEngine.RenderTexture(nWidth, nHeight, 0)
  14. cameraComponent.targetTexture = renderTexture
  15. cameraComponent:Render()
  16. CS.UnityEngine.RenderTexture.active = renderTexture
  17. local texture2D = CS.UnityEngine.Texture2D(nWidth, nHeight,
  18. CS.UnityEngine.TextureFormat.ARGB32, false)
  19. local rect = CS.UnityEngine.Rect(0, 0, nWidth, nHeight)
  20. texture2D:ReadPixels(rect, 0, 0)
  21. texture2D:Apply()
  22. cameraComponent.targetTexture = nil
  23. CS.UnityEngine.RenderTexture.active = nil
  24. CS.UnityEngine.GameObject.Destroy(renderTexture)
  25. return texture2D
  26. end
  27. function CameraShotHelper:CaptureCameraShot(cameraObj, nWidth, nHeight, szImageName)
  28. local texture2D = GetShotImage(cameraObj, nWidth, nHeight)
  29. local tBytes = texture2D:EncodeToPNG()
  30. -- save image
  31. if szImageName then
  32. CameraShotHelper:SaveShotImage(tBytes, szImageName)
  33. end
  34. return texture2D
  35. end
  36. return CameraShotHelper