Skip to content

Instantly share code, notes, and snippets.

@kanemu
Created August 10, 2011 08:09
Show Gist options
  • Save kanemu/1136345 to your computer and use it in GitHub Desktop.
Save kanemu/1136345 to your computer and use it in GitHub Desktop.
[illustrator]アートボードをオブジェクト全体に合わせる
#target "Illustrator"
function mergedBounds(bns,nowBns){
if(!bns){
bns=nowBns;
}else{
if(nowBns){
if(bns[0]>nowBns[0])bns[0]=nowBns[0];
if(bns[1]<nowBns[1])bns[1]=nowBns[1];
if(bns[2]<nowBns[2])bns[2]=nowBns[2];
if(bns[3]>nowBns[3])bns[3]=nowBns[3];
}
}
return bns;
}
function clipBounds(bns,clipping){
if(!bns){
bns=clipping;
}else{
if(clipping){
if(bns[0]<clipping[0])bns[0]=clipping[0];
if(bns[1]>clipping[1])bns[1]=clipping[1];
if(bns[2]>clipping[2])bns[2]=clipping[2];
if(bns[3]<clipping[3])bns[3]=clipping[3];
}
}
return bns;
}
function getAllBounds(item){
var items = item.pageItems;
var bns,clipping;
for(var i=0,l=items.length;i<l;i++){
var inner = items[i];
if(inner.clipping){
clipping = getItemBounds(inner);
}else{
var tmpBns = getItemBounds(inner);
if(tmpBns){
bns = mergedBounds(bns,tmpBns);
}
}
}
if(clipping){
bns = clipBounds(bns,clipping);
}
return bns;
}
function getItemBounds(item){
var typeName = item.constructor.name;
if(typeName==='Layer'){
if(item.visible){
return getAllBounds(item);
}
}else if(typeName==='GroupItem'){
if(item.clipped){
return item.pageItems[0].visibleBounds;
}else{
return getAllBounds(item);
}
}else{
if(!item.guides && !item.hidden){
return item.visibleBounds;
}
}
return;
}
//アートボードをアートワークのバウンディングボックスに合わせる
var fitArtboard = function(doc){
//アクティブなアートボードをとる
var board = doc.artboards[doc.artboards.getActiveArtboardIndex()];
var layers = doc.layers;
var bns_;
for(var i=0,l=layers.length;i<l;i+=1){
var bns = getItemBounds(layers[i]);
if(bns){
bns_ = mergedBounds(bns_,bns);
}
}
//$.writeln(bns_);
if(bns_){
//アートボードのサイズを設定
board.artboardRect = bns_;
}
};
fitArtboard(app.activeDocument);
#target "Illustrator"
//アートボードをアートワークのバウンディングボックスに合わせる
var fitToAllObject = function(doc){
//アクティブなアートボードをとる
var board = doc.artboards[doc.artboards.getActiveArtboardIndex()];
//オブジェクトを全てとる
var sels = doc.pageItems;
//0以上なら
if(sels.length > 0){
var bns;
for(var i=sels.length-1;i>=0;i--){
var sel = sels[i];
//ガイドか、隠されていたらスルー
if(sel.guides||sel.hidden)continue;
//レイヤーが非表示ならスルー
if(!sel.layer.visible)continue;
var nowBns = sel.visibleBounds;
if(!bns){
//bnsがなければ設定
bns = nowBns;
}else{
//あったら比較
if(bns[0]>nowBns[0])bns[0]=nowBns[0];
if(bns[1]<nowBns[1])bns[1]=nowBns[1];
if(bns[2]<nowBns[2])bns[2]=nowBns[2];
if(bns[3]>nowBns[3])bns[3]=nowBns[3];
}
};
//アートボードのサイズを設定
board.artboardRect = bns;
};
};
var doc = app.activeDocument;
fitToAllObject(doc);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment