October 23rd 2015 08:00:29am
Welcome to Free Function Friday. This week we are building a function that will return which directional length of a comp or footage asset is longer. This can be handy when you are trying to determine if an asset is portrait or landscape in nature. So if you wanted to place a landscape asset into a portrait comp, or vice versa, you can determine which side you will need to adjust your math on to make it fit correctly.
For our function we will be customizing the return data by using an object array. Object arrays are a very common way to return multiple bits of data together. Objects are denoted by the surrounding open and closing curly braces like so…
{}
The contents of an Object array are listed out similar to a normal Array in that each item is separated by a comma, but also requires an attribute name surrounded by single quotes, then a colon, and then the attribute value like this two item object array sample. The grey text is what you would replace with your own name and values.
var myValues = {
'attribute1Name': attribute1Value,
'attribute2Name': attribute2Value
}
By using different attribute names for each piece of data we can retrieve each attribute just like when you access attributes for any other object. For a Composition Object you normally can access attributes like…
var myComp = app.project.item(1); //Assumes first project item is a composition
myComp.name;
myComp.width;
myComp.height;
myComp.frameRate;
myComp.pixelAspect;
//etc…
This is because the object contains mulitiple values relating to that object. So to access our attribute2Value from the myValues variable, we would type…
myValues.attribute2Name;
For today’s function we will be creating our own attributes to return, one to return the resulting numerical value that is larger, and another to return a string representation of the longer side. In this case, we are using Width, Height, and Equal as our returned string options. You can certainly customize those strings to your liking, if you prefer a different naming.
If you haven’t done so already there is a Free Function Friday introduction video located here that has some important information pointing to a few resources that will come in handy when scripting for After Effects.
Source Code:
var a = app.project.item(1); //Assumes first item is Footage or Comp item
var b = longestSide(a);
alert(b.val);
/* TESTING ABOVE */
function itemLongestSide(avItem){
if(avItem instanceof FootageItem || avItem instanceof CompItem ){
var w = avItem.width;
var h = avItem.height;
var val = null;
if(w > h){/*width wins*/
val = {'val': w, 'dir':"Width"};
}else if(h > w){/*height wins*/
val = {'val': h, 'dir':"Height"};
}else if(w == h){/*tie*/
val = {'val': w, 'dir':"Equal"}
}
return val;
}
}