Skip to main content
hilukasz
Known Participant
January 29, 2010
Question

resize width of layer to canvas width

  • January 29, 2010
  • 2 replies
  • 2749 views

I'm having some trouble resizing a layer width to canvas width.

I know one way that works and it involves creating new document, resizing, then pasting back in. This seems extranious it seems there should be an easier way.

    var width = doc.width;
    var bounds = layer.bounds;
    var height = bounds[3]-bounds[1]; \\get height because I want this the same
    var width = doc.width;
    layer.resize (width, height, AnchorPosition.MIDDLECENTER);

this seems to fail even though it seems the documentation says it should work? maybe I am misunderstanding.

This topic has been closed for replies.

2 replies

Paul Riggott
Inspiring
January 29, 2010

When dealing with layers the resize is done with percentage, so your

layer width and height are allways 100% To make it fit the document you need to work out the ratio and then resize.

This should do what you want....

main();
function main(){
    if(!documents.length) return;   
    if (activeDocument.activeLayer.isBackgroundLayer) return;
    fitLayerToDoc();
}
function fitLayerToDoc(){  
var strtRulerUnits = app.preferences.rulerUnits;
var strtTypeUnits = app.preferences.typeUnits;
app.preferences.rulerUnits = Units.PIXELS;
app.preferences.typeUnits = TypeUnits.PIXELS;           
var docWidth = activeDocument.width.value;
var LB = activeDocument.activeLayer.bounds;              
var LWidth = LB[2].value - LB[0].value;               
var percentageWidth = ((docWidth/LWidth)*100);
activeDocument.activeLayer.resize(percentageWidth,100,AnchorPosition.MIDDLECENTER);
align( 'AdRg');
app.preferences.rulerUnits = strtRulerUnits;
app.preferences.typeUnits = strtTypeUnits;
}

function align(method) {
activeDocument.selection.selectAll();
   var desc = new ActionDescriptor();
           var ref = new ActionReference();
           ref.putEnumerated( charIDToTypeID( "Lyr " ), charIDToTypeID( "Ordn" ), charIDToTypeID( "Trgt" ) );
       desc.putReference( charIDToTypeID( "null" ), ref );
       desc.putEnumerated( charIDToTypeID( "Usng" ), charIDToTypeID( "ADSt" ), charIDToTypeID( method ) );
    try{
   executeAction( charIDToTypeID( "Algn" ), desc, DialogModes.NO );
   }catch(e){}
   activeDocument.selection.deselect();
};

hilukasz
hilukaszAuthor
Known Participant
February 3, 2010

this seems to work however, for some reason it still leaves out a few px on 3 sides when I use vector shape objects. not sure if this is a glitch, but as vector it seems to work perfect.

Inspiring
January 29, 2010

I would say either the layer and doc references are not valid or the layer is not visible.