Created
December 20, 2014 04:53
-
-
Save KzoNag/8bfb227585481048147d to your computer and use it in GitHub Desktop.
RectTransformのAnchorをオブジェクトのサイズに合わせるエディタ拡張
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEditor; | |
using System.Collections; | |
using System.Linq; | |
public static class RectTransformExtention | |
{ | |
[MenuItem("Util/RectTransform/Fit Anchors #t")] | |
static void FitAnchorsToTransform() | |
{ | |
var rectTransforms = from gameObject in Selection.gameObjects | |
where gameObject.GetComponent<RectTransform>() != null | |
select gameObject.GetComponent<RectTransform>(); | |
if (rectTransforms == null || rectTransforms.Count() <= 0) | |
{ | |
Debug.Log("No RectTransform is selected."); | |
return; | |
} | |
Undo.RecordObjects(rectTransforms.ToArray(), "Fit Anchors"); | |
foreach (var item in rectTransforms) | |
{ | |
FitAnchorsToTransform(item); | |
} | |
} | |
static void FitAnchorsToTransform(RectTransform rectTransform) | |
{ | |
var parent = rectTransform.parent as RectTransform; | |
if (parent == null) { return; } | |
// 親のピボットを原点とした座標系での値 | |
var leftPos = rectTransform.localPosition.x + rectTransform.rect.x; | |
var rightPos = leftPos + rectTransform.rect.width; | |
var bottomPos = rectTransform.localPosition.y + rectTransform.rect.y; | |
var topPos = bottomPos + rectTransform.rect.height; | |
var parentWidth = parent.rect.width; | |
var parentHeight = parent.rect.height; | |
var parentLeftPos = parent.rect.x; | |
var parentBottomPos = parent.rect.y; | |
var xMin = (leftPos - parentLeftPos) / parentWidth; | |
var xMax = (rightPos - parentLeftPos) / parentWidth; | |
var yMin = (bottomPos - parentBottomPos) / parentHeight; | |
var yMax = (topPos - parentBottomPos) / parentHeight; | |
// アンカーを設定 | |
rectTransform.anchorMin = new Vector2(xMin, yMin); | |
rectTransform.anchorMax = new Vector2(xMax, yMax); | |
// アンカーからの距離はゼロに設定 | |
rectTransform.offsetMin = Vector2.zero; | |
rectTransform.offsetMax = Vector2.zero; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment