LoginSignup
0
1

More than 5 years have passed since last update.

[illustrator_script]複数オブジェクト選択時のバウンディングボックスサイズの取得方法

Posted at

やりたいこと

複数オブジェクト選択時のバウンディングボックスのサイズを取得する。
よく使うのでメモ書きとして。

やったこと

以下実際のコードです。
本コードは取得したバウンディンングボックスのサイズでガイドを作成する仕様になっています。

getBounds.jsx
var doc = app.activeDocument;
var sels = doc.selection;

function getBoundsRect(target) {
    var rect = null;
    function updateRect(targetRect) {
        if (rect === null) {
            rect = targetRect;
            return;
        }
        if (rect[0] > targetRect[0]) {
            rect[0] = targetRect[0];
        }
        if (rect[1] < targetRect[1]) {
            rect[1] = targetRect[1];
        }
        if (rect[2] < targetRect[2]) {
            rect[2] = targetRect[2];
        }
        if (rect[3] > targetRect[3]) {
            rect[3] = targetRect[3];
        }
    }
    for (var i = 0, max = target.length; i < max; i++){
        updateRect(target[i].visibleBounds);
    }
    return rect;
}

// get size of selected obj's bounding box
var boundsRect = getBoundsRect(sels);

// create guide with size of bounding box
var rectObj = doc.pathItems.rectangle(
                      boundsRect[1],
                      boundsRect[0],
                      boundsRect[2] - boundsRect[0],
                      boundsRect[1] - boundsRect[3]
                      );                  
rectObj.guides = true;

解説

for (var i = 0, max = target.length; i < max; i++){
    updateRect(target[i].visibleBounds);
}

visibleBoundsプロパティは配列形式でオブジェクトのバウンディングボックスの座標を返します。
配列の中身は[左上X座標, 左上Y座標, 右下X座標, 右下Y座標,]となっています。

if (rect === null) {
    rect = targetRect;
    return;
}

1回目の処理は取得したvisibleBoundsをそのまま配列rectに代入します。

if (rect[0] > targetRect[0]) {
    rect[0] = targetRect[0];
}
if (rect[1] < targetRect[1]) {
    rect[1] = targetRect[1];
}
if (rect[2] < targetRect[2]) {
    rect[2] = targetRect[2];
}
if (rect[3] > targetRect[3]) {
    rect[3] = targetRect[3];
}

2回目以降の処理では取得したvisibleBoundの値によって配列rectの値を更新します。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1