获取选定的层

2022-09-04 00:00:00 javascript photoshop photoshop-script

与此question不同,是否有办法返回当前选定层的数组,不必循环所有层,从而删除/重新调整该选定内容?

function get_selected_layers()
{
  var layers = app.activeDocument.activeLayer;
 // only works with *last* selected layer
 // not *all* selected layers
}

var thelayers = get_selected_layers;
alert(thelayers);

解决方案

有点像,但不是真的。没有本机方法可以获取选定artLayer对象的数组。但是有一种操作管理器的方法来获取所选层的描述符-从描述符中可以获得您想要的一切。下面是一个返回所选层名称、索引和ID的数组的代码片段--对层描述符(desc)使用不同的getter可以获取其他所有内容。额外的好处是,如果您想获取artLayerDOM对象,可以通过ID选择artLayers。是的,这适用于群组和画板。

var layers = getSelectedLayersInfo();

// if we _really_ want to get artLayers we can select them one by one with IDs
for (var i = 0; i < layers.length; i++) {
  selectByID(layers[i].id);
  alert(activeDocument.activeLayer.name);
}

// and reselecting everything back
for (var i = 0; i < layers.length; i++) {
  selectByID(layers[i].id, true);
}


function getSelectedLayersInfo()
{
  var lyrs = [];
  var lyr;
  var ref = new ActionReference();
  var desc;
  var tempIndex = 0;
  var ref2;
  ref.putProperty(stringIDToTypeID("property"), stringIDToTypeID("targetLayers"));
  ref.putEnumerated(charIDToTypeID('Dcmn'), charIDToTypeID('Ordn'), charIDToTypeID('Trgt'));

  var targetLayers = executeActionGet(ref).getList(stringIDToTypeID("targetLayers"));
  for (var i = 0; i < targetLayers.count; i++)
  {
    ref2 = new ActionReference();

    // if there's a background layer in the document, AM indices start with 1, without it from 0. ¯\_(ツ)_/¯ 
    try
    {
      activeDocument.backgroundLayer;
      ref2.putIndex(charIDToTypeID('Lyr '), targetLayers.getReference(i).getIndex());
      desc = executeActionGet(ref2);
      tempIndex = desc.getInteger(stringIDToTypeID("itemIndex")) - 1;

    }
    catch (o)
    {
      ref2.putIndex(charIDToTypeID('Lyr '), targetLayers.getReference(i).getIndex() + 1);
      desc = executeActionGet(ref2);
      tempIndex = desc.getInteger(stringIDToTypeID("itemIndex"));
    }

    lyr = {};
    lyr.index = tempIndex;
    lyr.id = desc.getInteger(stringIDToTypeID("layerID"));
    lyr.name = desc.getString(charIDToTypeID("Nm  "));
    lyrs.push(lyr);
  }

  return lyrs;
}

function selectByID(id, add) {
    if (add == undefined) add = false;
    var desc1 = new ActionDescriptor();
    var ref1 = new ActionReference();
    ref1.putIdentifier(charIDToTypeID('Lyr '), id);
    desc1.putReference(charIDToTypeID('null'), ref1);
    if (add) desc1.putEnumerated(stringIDToTypeID("selectionModifier"), stringIDToTypeID("selectionModifierType"), stringIDToTypeID("addToSelection"));
    executeAction(charIDToTypeID('slct'), desc1, DialogModes.NO);
} // end of selectByID()

相关文章