首页 > 解决方案 > 如何通过 XD 中的插件获取文本元素的宽度值?

问题描述

我正在尝试为 XD 构建一个插件来自动创建设计元素。我编写了一个函数来使用文本元素和矩形构建按钮(下面的第一张图片)。唯一的问题是矩形的形状不是基于文本的宽度,所以当文本较长时,文本会与矩形重叠(见下图)。

基于固定大小矩形的按钮 基于显示溢出文本的固定大小矩形的按钮

我一直在试图弄清楚如何获取文本元素的宽度值,以便我可以适当地调整矩形的大小。谁能帮我这个?

我已经通过添加行console.log (selection.items);弄清楚了这一点。我可以将完整的属性列表输出到日志,但是如何访问 width 属性?

这是显示矩形和文本元素的日志输出...

[ Text ('Submit Button') {
    width: 113, height: 20
    global X,Y: -3, -74
    parent: Artboard ('iPad – 1')
    fill: ff000000
  },
  Rectangle ('Rectangle 6') {
    width: 100, height: 50
    global X,Y: -3, -58
    parent: Artboard ('iPad – 1')
    stroke: ff2d3494
  } ]

这是我的完整代码...

const {Rectangle, Color, Text, Selection} = require("scenegraph"); 
let commands = require("commands");

function createButton(selection) { 

    // Create the outline of the button
    const newButtonOutline = new Rectangle(); 
    newButtonOutline.width = 100;
    newButtonOutline.height = 50;
    newButtonOutline.stroke = new Color("#2D3494");
    newButtonOutline.strokeWidth = 2;
    newButtonOutline.cornerRadii = { 
        topLeft: 10, 
        topRight: 10, 
        bottomRight: 10, 
        bottomLeft: 10
    };

    // Create the text for the button
    const newButtonLabel = new Text();
    newButtonLabel.text = "Submit Button";
    newButtonLabel.fontSize = 18;
    newButtonLabel.fill = new Color("#000000");


    // Add the text and outline to the artboard
    selection.insertionParent.addChild(newButtonOutline);
    newButtonOutline.moveInParentCoordinates(100, 100);
    selection.insertionParent.addChild(newButtonLabel);
    newButtonLabel.moveInParentCoordinates(100, 100);
    selection.items = [newButtonLabel, newButtonOutline];
    console.log (selection.items);

    //align the button elements and group together 
    commands.alignHorizontalCenter();
    commands.alignVerticalCenter();
    commands.group();

}

我希望有人能帮帮忙!

标签: javascriptadobe-xd

解决方案


所以事实证明,要获取文本节点的宽度,您需要从 localBounds 获取它,比如......

textNode.localBounds.width

或者要获得图形节点的宽度,它只是......

图形节点宽度


推荐阅读