Created
January 22, 2022 05:18
-
-
Save hbouhadji/341208be65f00220723bf367cb718511 to your computer and use it in GitHub Desktop.
display aspect ratio by device pixels size
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function _pgcd(a, b) { | |
if (b) { | |
return _pgcd(b, a % b); | |
} else { | |
return Math.abs(a); | |
} | |
} | |
const createRatio = (width, height, color) => { | |
return { ratio: width / height, width, height, color }; | |
} | |
figma.currentPage.children.forEach(children => { | |
children.remove(); | |
}); | |
const deviceRect = figma.createFrame(); | |
deviceRect.resize(1920, 1080); | |
deviceRect.resize(3456, 2234); | |
const deviceAspectRatio = deviceRect.width / deviceRect.height; | |
const renderRatio = () => { | |
const pgcd = _pgcd(deviceRect.width, deviceRect.height); | |
const w = deviceRect.width / pgcd; | |
const h = deviceRect.height / pgcd; | |
if (w < 50 && h < 50) return `${w}:${h}`; | |
const deviceAspectRatioRounded = Math.round(deviceAspectRatio * 100) / 100; | |
return `${deviceAspectRatioRounded}:1`; | |
} | |
deviceRect.name = `${deviceRect.width}x${deviceRect.height} (${renderRatio()})`; | |
deviceRect.fills = [{type: 'SOLID', color: {r: 0, g: 0, b: 0}}]; | |
figma.currentPage.appendChild(deviceRect); | |
const ratios = [ | |
createRatio(16, 9, {r: 1, g: 0, b: 0}), | |
createRatio(16, 10, {r: 4/255, g: 206/255, b: 0}), | |
createRatio(4, 3, {r: 1, g: 199/255, b: 0}), | |
createRatio(18, 9, {r: 1, g: 0, b: 229/255}), | |
createRatio(21, 9, {r: 0, g: 26/255, b: 1}), | |
]; | |
ratios.forEach(ratio => { | |
const rect = figma.createRectangle(); | |
rect.name = ratio.width + ':' + ratio.height; | |
let newWidth = deviceRect.height * ratio.width / ratio.height; | |
let newHeight = deviceRect.width * ratio.height / ratio.width; | |
if (newWidth > deviceRect.width) { | |
newHeight = newHeight * deviceRect.width / newWidth; | |
newWidth = deviceRect.width; | |
} else if (newHeight > deviceRect.height) { | |
newWidth = newWidth * deviceRect.height / newHeight; | |
newHeight = deviceRect.height; | |
} | |
rect.resize(newWidth, newHeight); | |
rect.layoutAlign = 'CENTER'; | |
rect.fills = []; | |
rect.strokes = [ | |
{type: 'SOLID', color: ratio.color} | |
]; | |
rect.strokeWeight = 10; | |
rect.x = (deviceRect.width - rect.width) / 2; | |
rect.y = (deviceRect.height - rect.height) / 2; | |
deviceRect.appendChild(rect); | |
}); | |
// Make sure to close the plugin when you're done. Otherwise the plugin will | |
// keep running, which shows the cancel button at the bottom of the screen. | |
figma.closePlugin(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment