Skip to content

Instantly share code, notes, and snippets.

@cxmeel
Last active August 19, 2024 21:33
Show Gist options
  • Save cxmeel/78989d207a383e8f0fd6b78b4281b2fc to your computer and use it in GitHub Desktop.
Save cxmeel/78989d207a383e8f0fd6b78b4281b2fc to your computer and use it in GitHub Desktop.
React-lua hook for determining DPI scale.
local UserInputService = game:GetService("UserInputService")
local React = require(script.Parent.Parent.Packages.React)
local useState = React.useState
local useEffect = React.useEffect
local function calculateDpiScale()
local BUTTON_CONTENTID = UserInputService:GetImageForKeyCode(Enum.KeyCode.ButtonA)
local BUTTON_SCALE = BUTTON_CONTENTID:lower():match("@([%d%.]-)x%.%w+$")
return tonumber(BUTTON_SCALE or 1)
end
local function connectCamera(camera: Camera, setDpiScale)
return camera:GetPropertyChangedSignal("ViewportSize"):Connect(function()
setDpiScale(calculateDpiScale())
end)
end
local function useDpiScale()
local dpiScale, setDpiScale = useState(calculateDpiScale())
useEffect(function()
local viewportConnection = connectCamera(workspace.CurrentCamera, setDpiScale)
local changedConnection = workspace
:GetPropertyChangedSignal("CurrentCamera")
:Connect(function()
viewportConnection:Disconnect()
viewportConnection = connectCamera(workspace.CurrentCamera, setDpiScale)
end)
return function()
changedConnection:Disconnect()
viewportConnection:Disconnect()
end
end, {})
return dpiScale
end
return useDpiScale
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment